【问题标题】:chaining promise error handler链接承诺错误处理程序
【发布时间】:2014-03-14 20:52:59
【问题描述】:

请看演示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,它返回一个承诺。我正在那里处理错误,并将其返回(我在其中评论了 //do some processing )。我期待在客户端,它调用错误/失败处理程序。而是打印"SUCCESS --" + error

我可以使用 $qreject 来完成这项工作,但有没有办法没有?

【问题讨论】:

标签: javascript angularjs promise


【解决方案1】:

一般:

  • 每当您从 Promise 处理程序返回时,您都在解析表示正常流程继续。
  • 每当您承诺处理程序时,您都是在拒绝指示异常流程。

在同步场景中,您的代码是:

function get(url){
    try{
       return $http.get(url);
    } catch(err){
        //handle err
    }
}

如果你想进一步传递,你需要重新抛出:

function get(url){
    try{
       return $http.get(url);
    } catch(err){
        //handle err
        throw err;
    }
}

Promise 就是这样的:

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

或者使用更漂亮的语法:

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

【讨论】:

  • 感谢您的解释.. 效果很好。我没有注意到 promise (angular) has finally 和 catch before。
  • @bsr 其中一些是相当新的,但它发展得很好:) 很高兴我能提供帮助。
【解决方案2】:

return err替换为$q.reject(err),当然需要注入$q

在 Promise 链中,如果您想将错误传递下去,您需要从当前错误处理程序返回一个被拒绝的 Promise。否则,如果返回值是立即值或已解决的 Promise,则认为错误已处理,因此不会调用后续的错误处理程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 2014-08-12
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    相关资源
    最近更新 更多