簡體   English   中英

AngularJS http get 中的錯誤處理然后構造

[英]Error handling in AngularJS http get then construct

使用 AngularJS“http get then”構造(promises)時,如何處理 HTTP 錯誤,例如 500?

$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參數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM