简体   繁体   中英

Error handling in promises with catch

I have a question about error handling in $q promises. The code bellow does not work for handling errors outside of promises that are managed through controlled rejection or resolving through $q. Meaning, if the error is thrown anywhere in the code and not rejected, the catch block will not fire. Is there another way to have the catch be able to catch any error? 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.

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.

Is there a reason why $q promises aren't internally wrapped in a javascript try catch to guarantee that all errors can be handled.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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