- MERN Quick Start Guide
- Eddy Wilson Iriarte Koroliova
- 210字
- 2021-06-25 21:30:15
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) } })
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 function middleware expects to receive four arguments:
app.use((error, request, response, next) => { next(error) })
Take into account that next(error)is optional. That means, if specified, next(error) will pass control over to the next error handler. If no other error handler was defined, then the control will pass to the built-in error handler.