Volodymyr Frolov Volodymyr Frolov - 1 year ago 262
Javascript Question

In Node.js 7 what is the proper way to suppress UnhandledPromiseRejectionWarning?

In Node.js I have a module which consists of just one function. The function returns promise and the promise could be rejected. Still I don't want to force all users of the module to handle the rejection explicitly. By design in some cases it makes sense to just ignore the returned promise. Also I don't want to take the ability to handle the promise rejection away from module users.

What is the way to properly do so?

After upgrading to Node.js 7.1.0 all my unit tests which ignore rejection handling show the following warning:

(node:12732) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: try to throw an error from unit test
(node:12732) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

What is the proper way to prevent termination of Node.js process in the future mentioned in

Answer Source

This is not your problem to fix.

Just use promises the way they were intended. If the end user doesn't want to handle all rejections then THEY have to add an unhandledRejection handler. Otherwise they will need to add catches.

If your errors truly aren't breaking then you shouldn't be rejecting on them. Just resolve with an error value. e.g:

Success: resolve({result, error:null})

Failure: resolve({result:null, error})

It's still better to just reject and leave the end user to decide how to handle it.