This guide建议通过以下代码自定义处理 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'});
})
它没有按预期工作:它始终启动相同的“无法获取”错误,而不是自定义的错误。 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'
})
})
注意:上述处理程序应放在所有有效路由之后和错误处理程序之上。
但是,如果您想用相同的响应处理 404 和其他错误,您可以显式生成 404 错误。例如:
app.get('/someRoute',function(req, res, next) {
// If some error occurs 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'
})
})
这样,对于未找到的错误和所有其他业务逻辑错误,您的错误处理程序也会被调用。
关于node.js - Express.js 中的自定义错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47163872/