In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
My pipeline passed when it should have failed and deployed a version that is crashing on launch. If Node.js would have exited with a non-zero exit code, the pipeline would have failed and the bad version wouldn't have been deployed.
Is there a way to make Node.js exit with a non-zero exit code when it encounters an unhandled promise rejection, that doesn't require me to wait for the future?
If an error condition arises inside a promise, you “reject” the promise by calling the reject() function with an error. To handle a promise rejection, you pass a callback to the catch() function. This is a simple example, so catching the rejection is trivial.
The unhandledRejection event is emitted whenever a promise rejection is not handled. “Rejection” is the canonical term for a promise reporting an error. As defined in ES6, a promise is a state machine representation of an asynchronous operation and can be in one of 3 states: “pending”, “fulfilled”, or “rejected”.
A Promise rejection indicates that something went wrong while executing a Promise or an async function. Rejections can occur in several situations: throwing inside an async function or a Promise executor/then/catch/finally callback, when calling the reject callback of an executor , or when calling Promise.
The unhandledrejection event is sent to the global scope of a script when a JavaScript Promise that has no rejection handler is rejected; typically, this is the window , but may also be a Worker . This is useful for debugging and for providing fallback error handling for unexpected situations.
For node
12 and later:
node --unhandled-rejections=strict
Yes, you can, using the unhandledRejection
event on the process
object:
process.on('unhandledRejection', (reason, p) => {
console.error('Unhandled Rejection at:', p, 'reason:', reason)
process.exit(1)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With