kraftwer1
kraftwer1

Reputation: 5731

How to "catch" console.error()? (SO title)

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

Upvotes: 1

Views: 2035

Answers (2)

Anatolii Vasilev
Anatolii Vasilev

Reputation: 76

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;

Upvotes: 3

Manas Dixit
Manas Dixit

Reputation: 103

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

Upvotes: 0

Related Questions