1

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()?

3
  • You could try to replace the global console object, but oh boy is that a yucky and potentially error prone workaround…
    – deceze
    Oct 6, 2021 at 6:36
  • 1
    Fix the lib and submit a pull request?
    – TommyBs
    Oct 6, 2021 at 6:37
  • Which library is it, and where is the error statement in its code? There may be another way
    – CherryDT
    Oct 6, 2021 at 6:51

2 Answers 2

3

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;

1
  • 1
    Important gotcha: this approach won't work if the thing you are doing is asynchronous or may call other code though callbacks because then while it's running any other unrelated console error will also throw. Better to filter the message to identify known errors before attempting to throw them.
    – CherryDT
    Oct 6, 2021 at 6:54
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.