I included a lib that uses console.error()
instead of throw
.
Because of this, my try...catch
doesn't work. And because it's a 3rd party lib, I can't change their code.
Is there a (preferably elegant) workaround to "catch" a console.error()
?
CodePudding user response:
You cannot catch something that doesn't throw any errors. It looks like a crutch but you can override your console.error method in the code below. But don't forget that after you will have overriden console.error that throws errors!!!
console.errorWithoutExceptions = console.error;
console.error = (...messages) => {
console.errorWithoutExceptions(...messages);
throw new Error(messages[0]);
}
// now you can use
try {
// your code
console.error('test error');
} catch(e) {
// process you error with message 'test error' here
}
// don't forget to restore previous console.error after using
console.error = console.errorWithoutExceptions;
CodePudding user response:
You can try and manipulate the global console object to your requirement. But that's messy and might generate additional errors.
More here : Console | Node.js Docs