Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make nodejs terminate on unhandled promise rejections?

Tags:

node.js

I've got a bug in my code which is triggering the warning:

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.

Is there any way to make Node terminate when these happen?

like image 462
Andrew Avatar asked Jun 26 '17 01:06

Andrew


People also ask

How do you handle unhandled promise rejections?

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 happens on unhandled promise rejection?

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.

How do I terminate NodeJS?

Method 1: Using ctrl+C key: When running a program of NodeJS in the console, you can close it with ctrl+C directly from the console with changing the code shown below: Method 2: Using process. exit() Function: This function tells Node. js to end the process which is running at the same time with an exit code.

What is the preferred method of resolving unhandled exceptions in node JS?

Approach 1: Using try-catch block: We know that Node. js is a platform built on JavaScript runtime for easily building fast and scalable network applications. Being part of JavaScript, we know that the most prominent way to handle the exception is we can have try and catch block.


1 Answers

process will emit an unhandledRejection event for these, so:

process.on('unhandledRejection', error => {
    throw error;
});
like image 113
Ry- Avatar answered Sep 29 '22 07:09

Ry-