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:
specs found here
If we then look at the docs for
Promise.then
, we find:So doing
.catch()
will not actually catch anything and your app will continue throwing an error. You have to pass a function tocatch()
.Doing this will mute the error:
Updating to say that this is actually called out here at the top of the page, but I just missed it.