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

时间:2017-11-07 17:22:15

标签: node.js express error-handling

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和其他类型的错误?

2 个答案:

答案 0 :(得分:7)

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 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'}); 
    })

这样,您的错误处理程序也会因未找到错误和所有其他业务逻辑错误而被调用

答案 1 :(得分:0)

我不确定您要自定义错误消息的哪一部分,但是,如果您要更改 reason phrase ,请尝试以下操作:

app.use(function(err, req, res, next) {
    // console.log(err)
    res.statusMessage = "Route does not exist";
    res.status(401).end()
}

如果要包含正文,可以将.end()替换为.send()

相关问题