【问题标题】:JavaScript Capture handled ErrorsJavaScript 捕获处理的错误
【发布时间】:2016-09-06 23:13:46
【问题描述】:

我正在寻找一种解决方案,我可以在其中捕获浏览器控制台中记录的所有错误(已处理/未处理)。

我知道window.onerrorwindow.addeventlistener('error', function(){})

上面的代码只捕获未处理的错误。我还需要捕获已处理的错误。

例如:

function foo() {
  var x = null;
  try {
    x.a = "";
  } catch (e) {
    //Exception will be digested here.
  }

  var y = null
  y.b = "";
}

window.onerror = function() {
  //Write logic for the errors logged in console.
}

foo();

在上面的例子中try catch 在那里,所以我只会得到变量y 的错误,而不是x

有什么方法可以监听/捕获catch 块?

谢谢

【问题讨论】:

  • 您可以在使用调试器时做到这一点。但不是来自 JS 本身。为什么要这样做?
  • 如果你真的想要,你可以在你的 catch 之后抛出一个自定义错误,该错误将传递给 window.onerror。示例:fiddle.jshell.net/L29jv5fv 你想做什么?
  • @AlbertoRivera 同意,这可以通过抛出错误来实现。但我有一个需要消化异常的场景。
  • @Ankur 直接在catch里面调用函数怎么样? catch (e) {window.onerror('test',null,null,null,'custom');} 但是,请重新考虑您的方法。这似乎是错误的。

标签: javascript html ecmascript-6


【解决方案1】:

现实情况是,如果捕获到异常,那么这不是问题,因为您的代码知道如何处理它。

在其他编程语言(如 Java)中,只捕获您可以处理的异常,并将其他所有内容扔到链上更远的位置和/或映射到可能在调用堆栈更上层更有用的不同异常,这始终是一种好习惯。

例如:

function foo() {
  var x = null;
  try {
    x.a = "";
  } catch (e) {
    //Exception will be digested here.
    console.log("I am writing code here but still don't know how to proceed");
    throw new CustomError("Something was wrong");
  }

  var y = null
  y.b = "";
}

【讨论】:

    【解决方案2】:

    尝试手动调用 window.onerror。但是,请重新考虑改变您的方法。这太脏了。

    window.onerror = function(msg, url, lineNo, columnNo, error) {
      if (error === 'custom') {
       console.log("Handled error logged");
       return true;
      }
      console.log("unhandled error")
      return false;
    };
    

    示例尝试/捕获

    var myalert = function() {
      try {
        console.log(f);
      } catch (e) {
        window.onerror('test',null,null,null,'custom');
      }
      console.log("Gets here");
    }
    

    https://fiddle.jshell.net/L29jv5fv/2/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 2018-01-01
      • 1970-01-01
      • 2014-03-26
      相关资源
      最近更新 更多