javascript - AngularJS 中的 promise 是否捕获每个异常/错误?

标签 javascript angularjs promise

我在工作中继承了一个代码库,其中包含以下模式的十几个示例:

var promise = null;
try {
    promise = backendService.getResults(input);
}
catch (exception) {
    console.err(exception);
}
if (promise !== null) {
    promise.then(function (response) {
        // do stuff
    })
    .catch(function (error) {
        console.err(error);
    });
}

其中 backendService 是一个 Angular 服务,它又通过 $http 调用 REST 服务。

所以这是我的问题:try/catch 真的有必要吗?是否会出现特定错误/异常被 promise 的 .catch 捕获失败的情况?

整个上午团队都在争论这个话题,我们想出的唯一解决方案是我们认为没有必要,但是 (a)更改它会破坏与它一起编写的测试(也需要更改),并且(b)好吧......这是防御性编码,对吧?这不是坏事。

不过,当有更重要的事情要做时,实际上费心将它重构为遗忘的优点并不是我要问的。我只想知道当像这样传递 promises 时这是一个合理的模式(特别是在 AngularJS 中,如果这会有所作为),或者只是偏执狂。

最佳答案

Do promises in AngularJS catch every exception/error?

没有。只有从 then/catch callbacks 内部抛出的异常才会被自动捕获。在它们之外发生的所有错误都需要明确处理。

Will there ever be any scenario where a particular error/exception is thrown that the promise's .catch fails to catch?

是的。该 backendService.getResults(input) 调用可能不返回一个 promise ,但它可以抛出异常。或者,当 backendService 为 null 时,它甚至不会走那么远,你会得到一个 ReferenceError.getResults is not a function 并且你会得到一个 TypeError

is that try/catch really necessary?

不是真的。在后一种情况下,您的代码有严重错误,您可能不在乎抛出和崩溃。前一种情况,backendService.getResults(input) 抛出,被严重鄙视。 Asynchronous functions should never throw但只返回 promise - 正是因为您不必再​​编写两个错误处理语句。

well... it's defensive coding, right? It's not a Bad Thing.

是的,差不多。但这里值得商榷。同步异常在这里真的很意外,而不仅仅是一个可以处理故障的服务。 catch block 中的日志消息应该表示这一点。

请注意,它的防御性也不够。它没有捕捉到 getResults() 确实返回的可能更可能的错误,但不是 promise 。调用 .then() 可能会抛出异常。类似地,if (promise !== null) 是可疑的,因为当 null 被错误返回时它会隐藏(我们真的需要 try-catch-else 在这里)。

关于javascript - AngularJS 中的 promise 是否捕获每个异常/错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31678835/

相关文章:

javascript - 使用angular js更改文本外观

javascript - Node JS - 处理多个查询(promise,bluebird)

javascript - 通过粘性和默认排序功能对数组进行排序

javascript - 如何在 angularjs 中使用 ng-repeat 显示 JSON 数组?

javascript - 如何在 Angularjs 中创建嵌套的 json 对象

javascript - (babel插件)TypeError : Path was expected to have a container

javascript - 如何通过 ajax 将这个惰性分配转换为 promise ?

javascript - 使用模块模式和实例化新对象之间的区别

javascript - 单击任何菜单项时悬停属性丢失

javascript - 通过函数生成url后无法获取JSON