【问题标题】:How to avoid Node.Js app quit when there's a Javascript error?出现 Javascript 错误时如何避免 Node.Js 应用程序退出?
【发布时间】:2020-02-16 11:01:00
【问题描述】:

假设我的 Node.Js 应用 Javascript 代码中有以下错字:

    max_weight = Match.floor(max_weight/min_weight)

它应该是 Math.floor 而不是 Match.floor 所以当代码执行时我得到错误:

ReferenceError: Match is not defined

然后我的 Node.Js 应用退出。

如何确保即使出现此类错误,应用程序也不会退出,而是简单地报告错误并继续执行代码?

我知道我应该在投入生产之前解决这样的问题,但是,如果我希望代码在出现错误的情况下继续执行怎么办?

【问题讨论】:

    标签: javascript node.js error-handling


    【解决方案1】:

    通过将代码包装在 try catch 块中,您应该能够

    try {
      max_weight = Match.floor(max_weight/min_weight);
    }
    catch(err) {
      // do something to log error
    }
    

    请注意,try 块中发现错误之后的行将不会被执行。

    【讨论】:

      【解决方案2】:

      这可以通过两种方式实现。

      第一种方法是使用node.js全局错误处理方式:

      process.on('uncaughtException', function(err) {
        console.log(err); // do something with error or ignore it
      });
      
      let max_weight = 17, min_weight = 5;
      max_weight = Match.floor(max_weight / min_weight);
      

      其他方法是在代码级别本地处理它:

      try {
          // trying to do something that might fail should be inside try block
          let max_weight = 17, min_weight = 5;
          max_weight = Match.floor(max_weight/min_weight);
      } catch(err) {
          console.log(err); // do something with error or ignore it
      }
      

      克隆节点作弊error-handling,运行node error-handling.js

      【讨论】:

      • 那么这是否意味着如果我使用全局处理它不会再退出而只会做控制台日志?
      • 你不应该做的一件事是监听 uncaughtException 事件,发出 read here
      • 以上是特定于 OP 所要求的可能选项,目前尚不清楚 OP 是使用 express 还是 koa 或其他东西,否则响应可能会有点不同。
      猜你喜欢
      • 1970-01-01
      • 2021-03-26
      • 2017-04-14
      • 2013-06-21
      • 2018-08-26
      • 2012-02-22
      • 2020-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多