简体   繁体   中英

Express.js: global error handler middleware can not handle throw in middleware

I try to use middleware as router, here is my code:

// index.js
const router = require('./routers/router');
app.use('/api/a', router)

// router.js
const router = require('./routers/router');
const express = require('express');
const router = express.Router();

router.get('/', async (req, res, next) =>{
    try {
        throw new Error('error');
    }catch (e) {
       return next(e);
    }
    res.sendStatus(200);
})

module.exports = router;

and I try to catch this error on another middleware handler:

const handleRouterError = function (error, req, res) {
    res.status(500).send('Something broke!')
}

app.use('/api/a', router)
app.use(handleRouterError);

However, this doesn't work, because when run the server and try to access /api/a path, the error directly show on the page :

Error: error
    at /Users/expressjs-demo/routers/router.js:6:15

So what's wrong with my error handle code? How can I handle this error in the global error handler

The error handler middleware should be with 4 parameters:

app.use(function(err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

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