Getting UnhandledPromiseRejectionWarning even when catching exceptions

393 Views Asked by At

In NodeJS, I have some code like this:

function doSomethingAsync() {
    return Promise.reject("error");
}

function main() {
    doSomethingAsync().catch();
}

When I run this code, I get an UnhandledPromiseRejectionWarning.

I know that making my calling function async and awaiting doSomethingAsync inside of a try/catch makes the error go away, but in this case, I don't want to add the extra complexity of making the function async and awaiting just to mute an error, so I'd prefer to use catch().

Why doesn't my method of error handling mute the error?

1

There are 1 best solutions below

0
On BEST ANSWER

.catch() isn't actually catching anything.

If we look at the docs:

Internally calls Promise.prototype.then on the object upon which it was called, passing the parameters undefined and the received onRejected handler.

specs found here

If we then look at the docs for Promise.then, we find:

onRejected: A Function called if the Promise is rejected. This function has one argument, the rejection reason. If it is not a function, it is internally replaced with a "Thrower" function (it throws an error it received as argument).

So doing .catch() will not actually catch anything and your app will continue throwing an error. You have to pass a function to catch().

Doing this will mute the error:

doSomethingAsync().catch(() => { });

Updating to say that this is actually called out here at the top of the page, but I just missed it.