Writing error-handler middleware functions
ExpressJS already includes by default a built-in error handler which gets executed at the end of all middleware and route handlers.
There are ways that the built-in error handler can be triggered. One is implicit when an error occurs inside a route handler. For example:
app.get('/', (request, response, next) => { throw new Error('Oh no!, something went wrong!') })
And another way of triggering the built-in error handler is explicit when passing an error
as an argument to next(error)
. For instance:
app.get('/', (request, response, next) => { try { throw new Error('Oh no!, something went wrong!') } catch (error) { next(error) } })
Note
The stack trace is displayed on the client side. If NODE_ENV
is set to production, then the stack trace is not included.
A custom error handler middleware function can be written as well and it looks pretty much the same as route handlers do with the exception that an error handler...