How to handle all exceptions in node.js

后端 未结 2 1426
小蘑菇
小蘑菇 2020-12-31 00:29

After working for a couple of weeks with node.js, I found that there is a difference between node.js server errors and regular server side languages like PHP.

A si

相关标签:
2条回答
  • 2020-12-31 00:49

    You should simply validate the request data within your routes, catch any error (try-catch will work here since it's a sync operation) and handle it by returning appropriate HTTP status (e.g. 400) to the caller and log the error. If you're using Express you don't even have to use try-catch as Express will catch all synchronous exceptions and allow you to handle it centrally.

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

    • At this location, you have no context of where the error took place and can't send back a response to the caller
    • Any type of unhandled error will arrive here, if you've no idea what type of error occured it's recommended to restart the process. It doesn't make sense to restart the process because of invalid input, for example it's too easy this way to bring the app down for any external caller (DDOS)

    You may read here about other error handling best practices and specifically refer to bullets 4,6 and 10

    0 讨论(0)
  • 2020-12-31 00:55

    You can use the uncaughtException event on the process object to do what you want, but like others have said, domains and catching/handling errors at the correct level is recommended.

    process.on('uncaughtException', function(err) {
      console.log('Caught exception: ' + err);
    });
    
    0 讨论(0)
提交回复
热议问题