【问题标题】:Error handling in AngularJS http get then constructAngularJS http 中的错误处理然后构造
【发布时间】:2013-06-09 10:19:12
【问题描述】:

如何处理 HTTP 错误,例如500,当使用 AngularJS 的“http get then”构造(promises)时?

$http.get(url).then(
    function(response) {
        console.log('get',response)
    }
)

问题是,对于任何非 200 的 HTTP 响应,内部函数都不会被调用。

【问题讨论】:

    标签: javascript angularjs promise angular-promise angular-http


    【解决方案1】:

    你需要添加一个额外的参数:

    $http.get(url).then(
        function(response) {
            console.log('get',response)
        },
        function(data) {
            // Handle error here
        })
    

    【讨论】:

    • 请注意,上面的“响应”对象有:数据、状态、标题、配置、状态文本。上面的“数据”对象有:数据、状态、配置、状态文本。 (关于是否传递 statusText 有特殊规则 - 浏览器、移动设备与否、Web 服务器等)
    • 另请注意:data.config.url 包含完整的 url + params ,以防您在 url 旁边传递参数
    • 我不知道,但这不适用于我的情况。始终执行响应代码。
    【解决方案2】:

    您可以使用以下方法使这更清洁:

    $http.get(url)
        .then(function (response) {
            console.log('get',response)
        })
        .catch(function (data) {
            // Handle error here
        });
    

    类似于@this.lau_ 的回答,不同的方法。

    【讨论】:

    • 我完全赞成这个解决方案。
    • 它必须被接受,因为.error() 方法不适用于 500 错误!请接受。
    • v1.6.0中删除success & remove后的最佳解决方案
    • 注意如果.then 有内部错误(例如调用不存在的方法),.catch 也会执行,而.then(success, error) 将仅在请求本身失败时处理错误
    【解决方案3】:

    https://docs.angularjs.org/api/ng/service/$http

    $http.get(url).success(successCallback).error(errorCallback);
    

    将 successCallback 和 errorCallback 替换为您的函数。

    编辑:Laurent 的回答更正确,因为他使用的是then。然而,我将把它留在这里,作为将访问这个问题的人们的替代方案。

    【讨论】:

    • 值得一提的是,这与 Laurent 的回答不同。 .then() 返回一个承诺。 .success().error() 不这样做。
    • @james-brewer:更准确地说,.then() 返回一个 new 承诺。 .success().error() 没有,它们都返回 get(url) 提供的原始承诺。
    • 请记住,$http api 的 successerror 回调将被弃用。
    • 另外successerror也在v1.6.0中被删除,不能再使用了。
    • 另请注意,文档说“已弃用”,但 success() 和 error() 实际上已完全“删除”;不要被愚弄了。
    【解决方案4】:

    如果您想全局处理服务器错误,您可能需要为 $httpProvider 注册一个拦截器服务:

    $httpProvider.interceptors.push(function ($q) {
        return {
            'responseError': function (rejection) {
                // do something on error
                if (canRecover(rejection)) {
                    return responseOrNewPromise
                }
                return $q.reject(rejection);
            }
        };
    });
    

    文档http://docs.angularjs.org/api/ng.$http

    【讨论】:

    • 我认为你在这里犯了一个错误。要处理响应错误,您需要创建一个响应拦截器,而不是像您所做的那样创建请求拦截器。
    • 从 1.1.x 开始,Angular 的拦截器既是请求也是响应。
    【解决方案5】:

    试试这个

    function sendRequest(method, url, payload, done){
    
            var datatype = (method === "JSONP")? "jsonp" : "json";
            $http({
                    method: method,
                    url: url,
                    dataType: datatype,
                    data: payload || {},
                    cache: true,
                    timeout: 1000 * 60 * 10
            }).then(
                function(res){
                    done(null, res.data); // server response
                },
                function(res){
                    responseHandler(res, done);
                }
            );
    
        }
        function responseHandler(res, done){
            switch(res.status){
                default: done(res.status + ": " + res.statusText);
            }
        }
    

    【讨论】:

      【解决方案6】:

      我无法真正使用上述内容。所以这可能会对某人有所帮助。

      $http.get(url)
        .then(
          function(response) {
              console.log('get',response)
          }
        ).catch(
          function(response) {
          console.log('return code: ' + response.status);
          }
        )
      

      另请参阅$http response parameter

      【讨论】:

        猜你喜欢
        • 2014-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-22
        • 1970-01-01
        • 2014-01-07
        相关资源
        最近更新 更多