诺链接错误处理程序 [英] chaining promise error handler
本文介绍了诺链接错误处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请查看演示 rel=\"nofollow\">
Please see the demo here
function get(url) {
return $http.get(url)
.then(function(d){
return d.data
},
function(err){ //will work without handling error here, but I need to do some processing here
//call gets here
//do some processing
return err
})
}
get('http://ip.jsontest.co')
.then(function(response){
$scope.response = "SUCCESS --" + JSON.stringify(response);
}, function(err){
$scope.response = "ERROR -- " + err;
})
我有一个库函数, GET
,它返回一个承诺。我处理错误,并返回它(这里我评论 //做一些处理
)。我是在客户端期待,它会调用错误/失败的处理程序。相反,它打印的成功 - +误差
I have a library function, get
, which returns a promise. I am processing the error there, and returns it (where I commented //do some processing
). I was expecting in the client, it calls the error/fail handler. instead it prints "SUCCESS --" + error
我可以使这项工作 $ Q
和拒绝
,但有什么办法没有?
I can make this work with $q
and reject
, but is there a way without?
推荐答案
一般
- 当你的从一个承诺处理程序返回,你的解析指示正常流量延续。
- 当你的扔是在一个承诺处理程序,你的拒绝显示例外流程。
- Whenever you return from a promise handler, you are resolving indicating normal flow continuation.
- Whenever you throw at a promise handler, you are rejecting indication exceptional flow.
在一个同步场景中的code是:
In a synchronous scenario your code is:
function get(url){
try{
return $http.get(url);
} catch(err){
//handle err
}
}
如果您想进一步通过它,你需要重新抛出:
If you want to pass it further, you need to rethrow:
function get(url){
try{
return $http.get(url);
} catch(err){
//handle err
throw err;
}
}
承诺是完全一样的:
Promises are exactly like that:
function get(url){
return $http.get(url)
.then(function(d){
return d.data
},
function(err){ //will work without handling error here
//call gets here
//do some processing
throw err; // note the throw
})
};
或用甚至niftier语法:
Or with even niftier syntax:
function get(url){
return $http.get(url).catch(function(err){
// do some processing
throw err;
});
}
这篇关于诺链接错误处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文