【问题标题】:Best way to Handle Exception Globally in Node.js with Express 4?使用 Express 4 在 Node.js 中全局处理异常的最佳方法?
【发布时间】:2020-05-05 05:32:34
【问题描述】:

我们在 asp.net MVC 中有异常过滤器,我们在 node.js 中是否也有类似的功能和 express 4?

我尝试了以下文章,但没有找到所需的解决方案。

http://www.nodewiz.biz/nodejs-error-handling-pattern/

我在 app.js 上也试过了

process.on('uncaughtException', function (err) {
  console.log(err);
})

参考文章:http://shapeshed.com/uncaught-exceptions-in-node/

任何帮助都将不胜感激。

【问题讨论】:

    标签: javascript jquery asp.net-mvc node.js express


    【解决方案1】:

    错误可能来自并在不同位置捕获,因此建议在处理所有类型错误的集中对象中处理错误。例如,以下地方可能会出现错误:

    1.Web请求中出现SYNC错误时的Express中间件

    app.use(function (err, req, res, next) {
    //call handler here
    });
    

    2.CRON 作业(计划任务)

    3.你的初始化脚本

    4.测试代码

    5.来自某个地方的未捕获错误

        process.on('uncaughtException', function(error) {
     errorManagement.handler.handleError(error);
     if(!errorManagement.handler.isTrustedError(error))
     process.exit(1)
    });
    

    6.未处理的承诺拒绝

     process.on('unhandledRejection', function(reason, p){
       //call handler here
    });
    

    然后,当您捕获错误时,将它们传递给集中的错误处理程序:

        module.exports.handler = new errorHandler();
    
    function errorHandler(){
        this.handleError = function (error) {
            return logger.logError(err).then(sendMailToAdminIfCritical).then(saveInOpsQueueIfCritical).then(determineIfOperationalError);
        }
    

    更多信息read bullet 4' here(+ 其他最佳实践以及超过 35 个引用和代码示例)

    【讨论】:

      【解决方案2】:

      在 express 中,附加一个捕获所有错误处理程序是标准做法。 准系统错误处理程序看起来像

      // Handle errors
      app.use((err, req, res, next) => {
          if (! err) {
              return next();
          }
      
          res.status(500);
          res.send('500: Internal server error');
      });
      

      除此之外,您还需要在可能发生的任何地方捕获错误并将它们作为参数传递给next()。这将确保 catch all 处理程序捕获错误。

      【讨论】:

      • 因为我已经在谷歌上搜索并找到了这个解决方案,但我正在寻找类似 asp.net mvc 的异常过滤器的东西
      【解决方案3】:

      在节点中添加全局异常处理程序是process 上的事件。使用process.on 捕捉它们。

      process.on('uncaughtException', (err) => {
         console.log('whoops! there was an error');
      });
      

      【讨论】:

      • 它不会全局捕获异常。
      • @AshishKumar:你遇到了什么错误,你想捕捉什么?
      • 如果整个应用程序发生任何异常,那么它应该从一个地方处理。就像我们在 asp.net mvc 中使用异常过滤器一样。
      【解决方案4】:

      为 express js 中的所有路由编写一个中间件来处理如下所示

      function asyncTryCatchMiddleware(handler){
          return async (req,res,next) => {
             try{
                 await handler(req,res);
             } catch(e) {
                 next(e)
             }
          };
      }
      

      你可以像这样使用中间件:

      router.get('/testapi',asyncTryCatchMiddleware(async (req,res)=>{
          res.send();
      }));
      

      【讨论】:

        猜你喜欢
        • 2012-10-25
        • 2011-11-10
        • 2016-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多