Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get the future unhandled promise rejection behaviour now?

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?

like image 649
Erik B Avatar asked Aug 01 '18 12:08

Erik B


People also ask

How do you get unhandled Promise rejection?

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.

What is unhandled Promise rejection warning?

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”.

What causes Promise rejection?

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.

What are unhandled rejections?

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.


2 Answers

For node 12 and later:

node --unhandled-rejections=strict
like image 164
No_name Avatar answered Oct 06 '22 00:10

No_name


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)
});
like image 42
Thomas Avatar answered Oct 06 '22 01:10

Thomas