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

标签 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等错误?

最佳答案

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/

相关文章:

node.js - 将 NodeJS 流消耗到缓冲区并写入流的正确方法

node.js - Mongoose 、express 和 EJS 的奇怪行为

node.js - 错误 : Could not locate the bindings file. 已尝试:

c - 最终程序从 C 函数返回

php - 指示mod_php在脚本错误发生时发出html状态代码-可能吗?

javascript - 将对象从express公开到angularJS

node.js - 使用 node.js 应用程序和套接字 io 进行水平缩放

node.js - NodeJS Swig 数学

android - 改造2处理动态错误

node.js - 没有域的 SSL 证书