How to handle all exceptions in node.js

After working for several weeks with node.js, I found that there is a difference between node.js server errors and ordinary server language languages ​​such as PHP.

A simple example: if an error on our website occurs for any reason.

in php
If the user sends some invalid data to the server and MySQL, MySQL will give an error to this specific user, and the whole application will not go down.

at Nodejs
If the user sends some invalid data to the server and MySQL, the nodejs Server node will be omitted, and therefore all users will be disconnected, and communication between users will no longer be.

This is a really big problem. in large web applications. It is not possible to handle all errors to prevent the Nodejs server from dropping, and the question is


Is there a way to handle any unknown fatal errors and exceptions for a specific result, or something like that.

+6
source share
2 answers

You can use the uncaughtException event on the process object to do what you want, but as others have said, domains and traps / error handling at the correct level are recommended.

process.on('uncaughtException', function(err) { console.log('Caught exception: ' + err); }); 
+18
source

You should simply check the request data in your routes, catch any error (try-catch will work here, since this is a synchronization operation) and process it by returning the appropriate HTTP status (for example, 400) to the caller and registering the error. If you use Express, you don’t even need to use try-catch, as Express will catch all synchronous exceptions and allow you to handle it centrally.

I personally do not think that catching validation errors using process.on ('uncaughtException') is the best fit for your need for two main reasons:

  • At this point, you have no context where the error occurred, and cannot send a response to the caller
  • Any type of unhandled error will come here, if you do not know what type of error has occurred, it is recommended that you restart the process. It does not make sense to restart the process due to invalid input, for example, it is too simple to attach the application to any external caller (DDOS).

You can read here about other error handling methods and specifically refer to bullets 4.6 and 10.

+2
source

Source: https://habr.com/ru/post/957837/


All Articles