You can always override console.log
and do the special treatment for CustomError
yourself.
function CustomError(message = "") {
this.message = message;
//override toString to just return your message (or whatever you want your output to look like)
this.toString = () => this.message;
}
const ce = new CustomError("some message");
//this shows the builtin behaviour of console.log
console.log(ce);
//preserve the original console.log function, we'll need it later on
console.originalLog = console.log;
//override console.log with a new function
console.log = function() {
//check if any of the arguments is a CustomError
//and replace CustomErrors with its string representation
for (let i = 0; i < arguments.length; i++)
if (arguments[i] && arguments[i].constructor.name === "CustomError")
arguments[i] = arguments[i].toString();
//call the original log function with the updated arguments
console.originalLog.apply(this, arguments);
}
//this shows the overriden behaviour of console.log
console.log(ce);
//and back to original behaviour again
console.log = console.originalLog;
console.originalLog = undefined;
console.log(ce);
Probably not the most efficient or elegant solution, but it gets the job done in most scenarios. It won’t work, if the CustomError
is nested inside another object or array.
Make sure to preserve the original behaviour of console.log
in another variable, so you can use it, once you modified the arguments
.
CLICK HERE to find out more related problems solutions.