gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:12:38 26 4
gpt4 key购买 nike

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

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

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

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

我知道我可以中断调试器中的运行时错误异常,但我也可以通过这样做中断其他异常(在 jQuery 中),这意味着我必须在每次加载页面之前逐步执行 5 个 jQuery 异常我什至可以检查我自己的代码是否包含运行时错误。

有什么方法可以强制 promise 函数像往常一样记录运行时错误(无需为每个函数调用编写额外的代码)?

最佳答案

您遇到的问题是 then 回调中的异常确实拒绝了 .then() 返回的 promise ,而不是调用错误处理程序传入。这只会触发你调用 .then() 的 promise on 中的错误。所以你可以链接你的处理程序:

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

这里,then(null, …)也可以简写为catch(…)

如果没有done 方法在出现错误时throw,您可以自己实现它like this通过 throwing 在 setTimeout 中。

Is there any way to force the promise functions to log runtime errors like normal (without writing extra code for every function call)?

没有。那不是how they were designed .

关于javascript - 如何捕获 promise 运行时 Javascript 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22327568/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com