简体   繁体   English

带有承诺的承诺中的错误处理

[英]Error handling in promises with catch

I have a question about error handling in $q promises. 我对$ q promise中的错误处理有疑问。 The code bellow does not work for handling errors outside of promises that are managed through controlled rejection or resolving through $q. 下面的代码不适用于处理超出通过控制拒绝或通过$ q解决的承诺造成的错误。 Meaning, if the error is thrown anywhere in the code and not rejected, the catch block will not fire. 这意味着,如果错误在代码中的任何地方引发并且没有被拒绝,则catch块将不会触发。 Is there another way to have the catch be able to catch any error? 还有另一种方法可以使catch捕获任何错误吗? I know the call can be put in a try catch, but I was wondering if there is a way to make the $q catch behave like a regular javascript catch. 我知道可以将调用放在try catch中,但是我想知道是否有一种方法可以使$ q catch表现得像普通的javascript catch。

angular.module('myTest',[]).controller('myController',function($q){

    function someService(){
      var deferred = $q.defer();
      throw 'error';
      deferred.resolve({});
      return deferred.promise;
    } 

    someService().then(function(obj){
       console.log('then');
    }).catch(function(e){
      console.log(e);
    });

});

Is my only hope for handling all errors to do something like this: 我唯一希望处理所有错误以执行以下操作:

try
{
someService().then(function(obj){
   console.log('then');
});
}
catch(e){
  console.log('an error happened ' + e);
}

The use case her is that I am calling another service in someService() which throws an error that is out of my control, and I can't ensure that the promise is rejected. 她的用例是,我正在someService()中调用另一个服务,该服务抛出了我无法控制的错误,并且我无法确保承诺被拒绝。

Is there a reason why $q promises aren't internally wrapped in a javascript try catch to guarantee that all errors can be handled. 为什么$ q promises不会被内部包装在javascript try catch以确保所有错误都可以得到处理,这是有原因的。

You need to add an explicit reject statement when an error is thrown by a service. 服务抛出错误时,您需要添加一个显式拒绝语句。

var deferred =  $q.defer();
someService().then(function(obj){    
      deferred.resolve(obj):
   })
 .error(function(e){
    deferred.reject(e);
  });

 return deferred.promise;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM