简体   繁体   中英

Node.js Express handle errors function

In express app, I researched that we can handle error using something like this:

// app.js
app.use(function (error, req, res, next) {
    // Handle errors
});

my questions are:

  1. am I right that this function will be called only if there is an error? I could not get this function to call if there is no error. Am I missing anything?
  2. is there any case that this function will get called even there is no error?

Thanks

Yes. Middleware with arity of 4 (that is: err, req, res, next ) are error handlers, and will be called when there's an error.

Errors may be uncaught exceptions in your other middleware, or explicitly errors that you raise when you call next(err) instead of next() with no arguments.

There will be cases when these handlers won't be called. For example: errors that happen in async blocks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM