AngularJS中的错误处理:http get然后construct

Error handling in AngularJS http get then construct

本文关键字:http get 然后 construct 处理 错误 AngularJS      更新时间:2023-09-26

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

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

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

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

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

可以使用:

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

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

https://docs.angularjs.org/api/ng/service/http美元

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

用你的函数替换successCallback和errorCallback

编辑:考虑到他使用的是then, Laurent的答案更正确。但我还是把这个留到这里,作为将来访问这个问题的人的一个选择。

如果你想全局处理服务器错误,你可能需要为$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美元。

试试这个

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

我真的不能用上面的工作。所以这可能对某人有帮助。

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

参见$http response参数