66

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

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

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

4

6 回答 6

146

您需要添加一个附加参数:

$http.get(url).then(
    function(response) {
        console.log('get',response)
    },
    function(data) {
        // Handle error here
    })
于 2013-06-13T06:03:44.787 回答
58

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

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

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

于 2016-02-17T13:45:13.613 回答
14

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

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

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

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

于 2013-06-13T06:04:05.673 回答
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

于 2013-06-13T06:20:26.667 回答
2

尝试这个

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);
        }
    }
于 2016-03-07T09:17:53.477 回答
0

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

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

另见$http response参数

于 2019-06-13T15:39:38.677 回答