如何捕获promise运行时Javascript错误?

Woo*_*ome 6 javascript promise

我目前正在实现一个基于PDF.js的PDF查看器,作为我了解promise对象的一部分.

我还了解到调试控制台中不会自动显示运行时错误:

PDFJS.getDocument(...).then(
  function(pdfDocument){
    alert(UndefinedVariable); // Not shown in console!
  },
  function(error){
    console.log("Error occurred", error);
  }
);
Run Code Online (Sandbox Code Playgroud)

除了.done()http://www.asyncdev.net/2013/07/promises-errors-and-express-js/中描述的添加之外,我还没有找到在promise函数中显示运行时错误的漂亮方法.(这对PDF.js不起作用)或添加.catch(function(error){ console.error(error); }).

我知道我可以在调试器中打破运行时错误的异常,但是我也可以通过这样做来打破其他异常(在jQuery中),这意味着我必须在每个页面加载时执行5个jQuery异常,然后我才能检查我自己的代码是否包含运行时错误.

有没有办法强制promise函数像正常一样记录运行时错误(没有为每个函数调用编写额外的代码)?

Ber*_*rgi 7

您遇到的问题是,在一个异常then回调并拒绝返回的承诺.then(),而不是叫你传递的错误处理程序.这只会触发的承诺错误,你叫.then().所以你可以链接你的处理程序:

PDFJS.getDocument(...).then(function(pdfDocument){
    alert(UndefinedVariable); // Now shown in console!
}).then(null, function(error){
    console.log("Error occurred", error);
});
Run Code Online (Sandbox Code Playgroud)

在这里,then(null, …)也可以缩写catch(…).

如果没有done该方法throws的错误,你可以实现它自己喜欢这个throw荷兰国际集团的setTimeout.

有没有办法强制promise函数像正常一样记录运行时错误(没有为每个函数调用编写额外的代码)?

不,那不是他们的设计方式.