2016-08-07 3 views
1

그래서 매번 응답으로 200을 반환하는 서버가 있습니다. 오류에 대한 응답을 확인해야합니다. response.data.error 오류가 발견되면 http 요청을 응용 프로그램 코드의 catch 메서드에 보내야합니다. 여기

은 .. 내가 일이 원하는의 예입니다

요격 코드

// interceptor code 
{ 
    response:function(response){ 
    if (response.data.error) { 
     return $q.reject(response) 
    }else{ 
     return response 
    } 
    }, 
    responseError:function(rejection){ 
    // error handling logic 

    return $q.reject(rejection) 
    } 
} 

응용 프로그램 코드는

// application code 
$http.get('/api/stuff') 
    .then(function(){ 
    // do success stuff 
    }).catch(function(){ 
    // the function i want to run!!! 
    }) 
+0

'$ http.get ('aaa')'와 같이 임의 ** URL **을 입력하면 어떻게됩니까? 'catch '를 호출합니까? – developer033

+0

게시 된 코드가 예상대로 작동해야합니다. 이 접근 방식에 문제가있는 경우 [MCVE] (http://stackoverflow.com/help/mcve)에 fiddle/plunk를 제공하십시오. – estus

+0

오케이 soooo가 내 응용 프로그램과 뭔가 있어야합니다. 방금 plunkr을 만들었고 https://plnkr.co/edit/ZpwSMW66EnUtP78QhVV9?p=preview –

답변

1

네, 어리석은 실수였습니다. 여기 내가 잘못한 것이있다.
벙어리 i처럼 응답 대신 직접 함수 내부로 반환됩니다. 그래서 내가 끝낸 일은 깃발을 만드는 것이고, 그 깃발이 사실이라면 응답 함수를 직접적으로 반환합니다.

요격 코드

// interceptor code 
{ 
    response:function(response){ 
    myCustomErrorFunction(){ 
     if (response.data.error) { 
     return $q.reject(response) 
     }else{ 
     return response 
     } 
    } 
    }, 
    responseError:function(rejection){ 
    // error handling logic 

    return $q.reject(rejection) 
    } 
} 

응용 프로그램 코드 도움말들에 대한

// application code 
$http.get('/api/stuff') 
    .then(function(){ 
    // do success stuff 
    }).catch(function(){ 
    // the function i want to run!!! 
    }) 

감사합니다.

0

에 의해 오류를 잡는보십시오 :

$http.get('/api/stuff') 
    .then(function(data){ 
    console.log(data); // do success stuff 
    }, function(error){ 
     console.log(error); // will catch your error I hope 
    } 

나는 생각하지 않는다. 모자 .catch을 보내면 .then 블록의 수표를 만들어야합니다.

관련 문제