本指南建议通过以下代码自定义处理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和其他类型的错误?
发布于 2017-11-07 17:52:00
Not或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'
})
})通过这种方式,您的错误处理程序也会被调用,以找不到错误和所有其他业务逻辑错误。
发布于 2019-11-22 22:17:11
但是,如果您想要更改https://www.ibm.com/support/knowledgecenter/en/SSGMCP_5.1.0/com.ibm.cics.ts.internet.doc/topics/dfhtl_httpstatus.html,请尝试如下所示:
app.use(function(err, req, res, next) {
// console.log(err)
res.statusMessage = "Route does not exist";
res.status(401).end()
}如果您想要包含一个主体,可以用.end()替换.send()。
https://stackoverflow.com/questions/47163872
复制相似问题