首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Express.js中的自定义错误处理

Express.js中的自定义错误处理
EN

Stack Overflow用户
提问于 2017-11-07 17:22:14
回答 2查看 5.6K关注 0票数 3

本指南建议通过以下代码自定义处理Express.js中的错误:

代码语言:javascript
复制
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和其他类型的错误?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-11-07 17:52:00

Not或404在默认情况下不是应用程序错误,只有在传递任何路由的下一个参数中的错误时才调用必须定义的处理程序。为了处理404,您应该使用一个没有错误的处理程序。

代码语言:javascript
复制
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生成一个错误。例如:

代码语言:javascript
复制
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'
    })
})

通过这种方式,您的错误处理程序也会被调用,以找不到错误和所有其他业务逻辑错误。

票数 14
EN

Stack Overflow用户

发布于 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,请尝试如下所示:

代码语言:javascript
复制
app.use(function(err, req, res, next) {
    // console.log(err)
    res.statusMessage = "Route does not exist";
    res.status(401).end()
}

如果您想要包含一个主体,可以用.end()替换.send()

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47163872

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档