【问题标题】:No errors in console.log unless using try/catch除非使用 try/catch,否则 console.log 中没有错误
【发布时间】:2019-08-27 12:29:40
【问题描述】:

通常所有错误都会显示在浏览器控制台中,例如如果变量未定义。这次不行。除非我使用 try/catch,否则不会显示任何错误。

我不确定是什么原因。我开始了一个新项目,并使用了 webpack、babel 和一堆其他 webpack 相关库。 (列表见底部)

所以问题是:

x = abc;
console.log("here");

“这里”没有显示,因为代码在该行停止。 x = abc; 我没有看到任何编译错误/警告。

try {
    x = abc;
} catch (error) {
    console.log("Error: " + error.message);
}
console.log("here");

输出:

Error: abc is not defined
here

知道为什么吗?从来没有遇到过这样的问题。而且我没有包装尝试/捕获。 这是我在 package.json 中加载的内容:

//编辑:

这是我正在使用的代码:

abj.SomePromise().then((response) => {
    let c= aa;  //this should generate an error
    //this wont be shown:
    console.log('Everything loaded');
});

【问题讨论】:

  • 看起来其他东西正在捕获异常。也许是 window.onerror 或类似的东西?
  • 您可以打开调试控制台并输入console.log(window.onerror) 作为快速实验。
  • 我检查了,window.onerror 为空(document.onerror 也为空)
  • 我刚刚发现那是因为我在承诺中使用了错误(在“then”部分)
  • 这就是为什么分享实际代码而不是你认为有用的信息很重要的原因。我一直在到处看到这种模式,开发人员根据他们对错误的假设提出问题。

标签: javascript ecmascript-6 error-handling


【解决方案1】:

因为执行是从上到下的,

第一种情况

x = abc;
console.log('here');

在第一种情况下,您的执行过程将被停止并杀死,因为它没有被处理,那时您的服务器将崩溃并在控制台中得到ReferenceError: abc is not defined,并且不会打印here

第二种情况

try {
  x = abc;
} catch (error) {
  console.log(`Error: ${error.message}`);
}
console.log('here');

在这种情况下,使用try/catch 正确处理错误,

第二种情况的解释

在这种情况下,它首先执行try{} 块中的任何内容,然后执行try 中写入的任何内容,这里您创建一个变量x,其值为abc,但abc 没有定义,所以它将throw 出错,所以这里catch() {} 块将进入图片并执行catch() {} 块中的任何写入; 所以它打印Error: abc is not defined,然后trycatch都完成了他的工作;然后继续执行到底部进行进一步操作。它找到另一个日志console.log("here"); 所以它打印here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 2021-06-10
    • 2021-05-04
    • 2016-05-04
    • 2021-06-03
    • 1970-01-01
    相关资源
    最近更新 更多