Node.js(Express)错误处理中间件与路由器 [英] Node.js (Express) error handling middleware with router
问题描述
这是我的申请结构:
- app.js
- routes
---- index.js
ExpressJS
应用创建错误开发
和生产
环境的处理程序。这是来自 app.js的代码片段
:
The ExpressJS
app creates error handlers for development
and production
environments. Here's a code snippet from app.js
:
app.use('/', routes); // routing is handled by index.js in the routes folder
//The following middleware are generated when you create the Express App
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error.ejs', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
在 routes / index.js
内,我处理所有路由:
And inside of routes/index.js
, where I handle all the routing:
var router = express.Router();
router.get('/', function (req, res) {
someAsyncFunction(function(err, result) {
if (err) throw err; // Handle this error
}
});
module.exports = router;
我希望将错误
传递给其中一个错误处理程序而不是抛出。我该怎么做?
I want the err
to be passed to one of the error handlers instead of being thrown. How can I do this?
推荐答案
你必须把它传递给下一个回调,它通常是路由处理程序中的第三个参数
You have to pass it to the next callback which is usually the third parameter in the route handler
var router = express.Router();
router.get('/', function (req, res, next) {
someAsyncFunction(function(err, result) {
if (err) {
next(err); // Handle this error
}
}
});
module.exports = router;
调用 next (错误)
将允许使用以下签名在链中的中间件中捕获错误:
calling next(err)
will allow the error to be caught in a middleware down the chain with the following signature:
app.use(function (err, req, res, next){
// do something about the err
});
参考: http://expressjs.com/en/guide/error-handling.html
这篇关于Node.js(Express)错误处理中间件与路由器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!