0

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

4

1 回答 1

2

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.

于 2013-09-13T05:56:19.137 回答