简体   繁体   中英

How does the Error Handler work?

How does the the error handler get triggered?

In sample code, I find that it is placed at the bottom of all the middleware functions. Is the position important?

You can refer below example for some details. Here, for the '/' GET endpoint a middleware explicitly throws an error 'problem error'. At this point, express error handler mechanism is triggered and it looks for an error handler (with err as a param). As a result, subsequent 'Hello' is not sent back to the client as its handler is not an error one.

Subsequent error handlers logErrors, clientErrorHandler and errorHandler are invoked one by one to perform relevant tasks with final one writing back the response.

The reason they are placed at the end is to catch the errors thrown by declared middlewares and handle them elegantly ie printing it, logging it, sending mails etc. Think of it in terms of a try catch mechanism in other languages like Java. If declared above other middlewares, they would render useless as the errors won't be handled. You can see the difference in output by swapping the order of 'GET' request with the error handlers.

 const express = require('express'); const app = express(); app.get('/', (req, res, next) => next(new Error('problem error')), (req, res) => { res.status(200).send("Hello"); }); app.use(logErrors); app.use(clientErrorHandler); app.use(errorHandler); function logErrors (err, req, res, next) { console.error(err.stack) next(err) } function clientErrorHandler (err, req, res, next) { if (req.xhr) { res.status(500).send({ error: 'Something failed!' }) } else { next(err) } } function errorHandler (err, req, res, next) { if (res.headersSent) { return next(err) } res.status(500) res.render('error', { error: err }) } app.listen(3000, () => console.log('Example app listening on port 3000!')) 

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