M-e*_*man 2 error-handling node.js express
本指南建议通过以下代码自定义处理Express.js中的错误:
app.use(function(err, req, res, next) {
// Do logging and user-friendly error message display
console.error(err);
res.status(500).send({status:500, message: 'internal error', type:'internal'});
})
Run Code Online (Sandbox Code Playgroud)
它不能按预期工作:它始终启动相同的"无法获取"错误而不是自定义错误.如何使用Express处理404和其他类型的错误?
Not Found或404默认情况下不是应用程序错误,只有在任何路由的下一个参数中传递错误时,才会调用已定义的处理程序.对于处理404你应该使用没有错误的处理程序
app.use(function(req, res, next) {
// Do logging and user-friendly error message display
console.log('Route does not exist')
res.status(500).send({status:500, message: 'internal error',type:'internal'});
})
Run Code Online (Sandbox Code Playgroud)
注意: - 上面的处理程序应该放在所有有效路由之后和错误处理程序之上.
但是,如果您想要使用相同的响应处理404和其他错误,则可以显式生成404的错误,例如:
app.get('/someRoute,function(req,res,next){
//if some error occures pass the error to next.
next(new Error('error'))
// otherwise just return the response
})
app.use(function(req, res, next) {
// Do logging and user-friendly error message display
console.log('Route does not exist')
next(new Error('Not Found'))
})
app.use(function(err, req, res, next) {
// Do logging and user-friendly error message display
console.error(err);
res.status(500).send({status:500, message: 'internal error',
type:'internal'});
})
Run Code Online (Sandbox Code Playgroud)
这样,您的错误处理程序也会因未找到错误和所有其他业务逻辑错误而被调用
| 归档时间: |
|
| 查看次数: |
1248 次 |
| 最近记录: |