AngularJS - 承诺重新抛出捕获的异常 [英] AngularJS - Promises rethrow caught exceptions

查看:1608
本文介绍了AngularJS - 承诺重新抛出捕获的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下code,一个例外是在抓陷入的$ Q承诺的功能:

In the following code, an exception is caught by the catch function of the $q promise:

// Fiddle - http://jsfiddle.net/EFpn8/6/
f1().then(function(data) {
        console.log("success 1: "+data)
        return f2();
    })
    .then(function(data) {console.log("success 2: "+data)})
    .catch(function(data) {console.log("error: "+data)});

function f1() {
    var deferred = $q.defer();
    // An exception thrown here is not caught in catch
    // throw "err";
    deferred.resolve("done f1");        
    return deferred.promise;
}

function f2() {
    var deferred = $q.defer();
    // An exception thrown here is handled properly
    throw "err";
    deferred.resolve("done f2");        
    return deferred.promise;
}  

然而,当我看到在控制台日志输出我看到以下内容:

However when I look in the console log output I see the following:

例外被捉住了角,但也受到浏览器的错误处理捕获。此行为不会重现符合Q库。

The exception was caught in Angular, but was also caught by the error handling of the browser. This behavior does reproduce with Q library.

它是一个错误吗?我怎样才能真正符合$ Q捕获异常?

Is it a bug? How can I truly catch an exception with $q?

推荐答案

角的 $ Q 使用惯例的地方抛出的错误记录的无论的被抓。相反,如果你想你的信号需要拒绝收益$ q.reject(... 这样:

Angular's $q uses a convention where thrown errors are logged regardless of being caught. Instead, if you want to signal a rejection you need to return $q.reject(... as such:

function f2() {
    var deferred = $q.defer();
    // An exception thrown here is handled properly
    return $q.reject(new Error("err"));//throw "err";
    deferred.resolve("done f2");        
    return deferred.promise;
}  

这是从喜欢的SyntaxError的错误区分拒绝。就个人而言,这是一个设计选择,我不同意,但它因为 $ Q 理解的是微小的,所以你不能真正建立在可靠的未处理的排斥反应检测机制。在像蓝鸟更强库,则不需要这样的事情。

This is to distinguish rejections from errors like SyntaxError. Personally, it's a design choice I disagree with but it's understandable since $q is tiny so you can't really build in a reliable unhandled rejection detection mechanism. In stronger libraries like Bluebird, this sort of thing is not required.

作为附带说明 - 永远,永远扔字符串:您堆栈跟踪错过这样

As a side note - never, ever throw strings : you miss on stack traces that way.

这篇关于AngularJS - 承诺重新抛出捕获的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆