[英]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 :但是,这不起作用,因为当运行服务器并尝试访问/api/a
路径时,错误直接显示在页面上:
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:错误处理程序中间件应该有 4 个参数:
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.