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 await
ing 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?
.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 parametersundefined
and the receivedonRejected
handler.
specs found here
If we then look at the docs for Promise.then
, we find:
onRejected
: AFunction
called if thePromise
is rejected. This function has one argument, therejection 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.