programing tip

AngularJS http get then Construct에서 오류 처리

itbloger 2020. 11. 16. 07:55
반응형

AngularJS http get then Construct에서 오류 처리


AngularJS "http get then"구성 (약속)을 사용할 때 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_ 답변과 유사하게 다른 접근 방식입니다.


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

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

successCallback 및 errorCallback을 함수로 대체하십시오.

편집 : Laurent의 대답은 그가 then. 그러나 나는이 질문을 방문 할 사람들을위한 대안으로 여기에 남겨두고있다.


서버 오류를 전역 적으로 처리하려면 $ 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);
        }
    }

I could not really work with the above. So this might help someone.

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

See also the $http response parameter.

참고URL : https://stackoverflow.com/questions/17080146/error-handling-in-angularjs-http-get-then-construct

반응형