简体   繁体   English

链许诺错误处理程序

[英]chaining promise error handler

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;
      })

I have a library function, get , which returns a promise. 我有一个库函数get ,它返回一个promise。 I am processing the error there, and returns it (where I commented //do some processing ). 我在那里处理错误,并将其返回(我在其中注释//do some processing )。 I was expecting in the client, it calls the error/fail handler. 我在客户端中期望它会调用错误/失败处理程序。 instead it prints "SUCCESS --" + error 而是显示"SUCCESS --" + error

I can make this work with $q and reject , but is there a way without? 我可以使用$qreject此工作,但是有没有办法吗?

Replace return err with $q.reject(err) , you need to inject $q of course. return err替换为$q.reject(err) ,您当然需要注入$q

In promise chaining, if you want to pass the error down, you'll need to return a rejected promise from current error handler. 在诺言链中,如果您想将错误传递给其他人,则需要从当前的错误处理程序返回被拒绝的诺言。 Otherwise, if the return value is an immediate value or resolved promise, the error is considered to be handled, so later error handlers down the chain won't be called. 否则,如果返回值是立即值或已解决的Promise,则认为该错误已得到处理,因此不会调用链中后来的错误处理程序。

Generally: 通常:

  • 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. 每当您承诺处理程序扔东西时,您都将拒绝指示异常流。

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
      })
  };

Or with even niftier syntax: 甚至使用niftier语法:

function get(url){
     return $http.get(url).catch(function(err){
           // do some processing
           throw err;
     });
}

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

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