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

1 Answer 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.

Sign up to request clarification or add additional context in comments.

1 Comment

very useful info and quick reply. Appreciated @Nitzan Shaked. +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.