【问题标题】:throw new Error(string) not showing in F12抛出新的错误(字符串)未在 F12 中显示
【发布时间】:2016-10-30 16:45:49
【问题描述】:

我有一个抛出 Error 的 JS 脚本

$.when(verifyInitArgs(initArgs))
    .then(function argsAreValid() {
        initialiseForm();
    }, function argsInvalid(error) {
        throw new Error(error);
    });

error 变量是string。设置断点时,我可以通过 typeof 看到这一点:

>> typeof error
"string"

但是,抛出的错误不会显示在 IE 或 Firefox 的控制台窗口中。

如果我直接在浏览器控制台中输入throw new Error("something");,那么它会按预期工作,它会在控制台中显示为错误。

这里发生了什么?

【问题讨论】:

  • 您使用的是什么版本的 jQuery?这可能很重要,因为他们一直试图使其 Deferred 对象符合 Promises/A+ 规范。
  • @T.J.Crowder 3.1.1m 但是我可以看到承诺没问题,因为我可以在throw 行上打断点并查看error 的值。

标签: javascript jquery error-handling


【解决方案1】:

回想一下 then(和 catch 等)创建了一个 new 承诺,您的回调中的代码可以影响结果。在 Promises/A+ 风格的 Promise 中(JavaScript 的原生 Promise 遵循这些语义,而 jQuery 一直在尝试使 Deferreds 符合要求——我相信您现在使用的 v3.1.1 符合要求),当你抛出一个 Promise 时thencatch 回调,该异常将转换为对 thencatch 方法创建的承诺的拒绝。

因此,您的 throw new Error(...) 正在拒绝您对 then 的调用返回的承诺。

浏览器正在更新他们对未处理的拒绝的处理,以便它们出现在控制台中(目前对此的支持有所不同);切换到原生 Promise 可能是值得的。

只是为了说明,下面是一个在 then 回调中抛出原生承诺的示例:

new Promise(function(resolve) {
  console.log("First promise resolving");
  resolve("all good");
}).then(function(resolution) {
  console.log("Got resolution " + resolution);
  console.log("Throwing error from second promise");
  throw new Error("ack!");
});

在最近的 Chrome 中,当你运行它时,如果你打开真正的控制台(不仅仅是 in-sn-p 控制台),你会看到

未捕获(承诺)错误:确认!(...)

...报告未处理的拒绝。

相比之下,使用 jQuery v3.1.1,我看不到那个错误:

var d = $.Deferred();
d.promise().then(function(resolution) {
  console.log("Got resolution " + resolution);
  console.log("Throwing error from second promise");
  throw new Error("ack!");
});
console.log("First promise resolving");
d.resolve("all good");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

...这就是为什么切换到原生 Promise 可能有用的原因(如果在您的项目中可行的话)。

【讨论】:

  • 可能更容易使用console.error("Eek")。只要它没有默默地失败,我就很高兴。
  • @BanksySan: :-) 确实。
猜你喜欢
  • 1970-01-01
  • 2018-12-05
  • 1970-01-01
  • 2014-02-27
  • 2013-04-12
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多