2017-11-27 6 views
0

다음과 같이 서버에서 항목을 가져 오는 작업 API가 있습니다. 나는이 데이터를 사용하기 위해 React를 사용하고있다. 이제 5__로 시작하는 모든 서버 오류를 포착하고 "인터넷 연결 없음"또는 이와 비슷한 메시지를 표시하려고합니다.React에서 JavaScript (Gateway Timeout) 오류 캐치

export const GetItems = (operand, searchValue) => { 
     const trimmedValue = searchValue.trim(); 
     let combinedResults; 
     // make 2 API calls to search on both item_name and code; 
     // then combine them; 
     // there is no API method to do this, that I could find 
     return getItemsByName(operand, trimmedValue) 
     .then(result => (
     (combinedResults = [].concat(result)) 
    )) 
     .then(() => getItemsByCode(operand, trimmedValue)) 
     .then(result => (
     (combinedResults = combinedResults.concat(result)) 
    )); 
    }; 

현재 콘솔에 연결 문제가 있는지 확인해야합니다. @Dane으로 업데이트


504 Gateway Timeout Error

그것은 단지 URL을 구축하는 방법을 부르고

const getItemsByCode = (operand, searchValue) => (
    FetchToJson(BuildCodeSearchUrl(operand, searchValue)) 
); 

을 요청했다. 모든 것이 잘 작동하고 있다고 생각할 수 있습니다. 연결이 있으면 응답을받습니다.

+0

당신이뿐만 아니라'getItemsByCode'에 대한 코드를 추가시겠습니까? – Dane

+0

와트 http 라이브러리를 사용하고 있습니까? – Panther

답변

1

사용 catch() :

return getItemsByName(operand, trimmedValue) 
     .then(result => (
     (combinedResults = [].concat(result)) 
    )) 
     .then(() => getItemsByCode(operand, trimmedValue)) 
     .then(result => (
     (combinedResults = combinedResults.concat(result)) 
    )) 
     .catch((error) => { 
     if (error.response) { // if there is response, it means its not a 50x, but 4xx 

     } else { // gets activated on 50x errors, since no response from server 
      // do whatever you want here :) 
     }    
     }); 
+0

감사합니다. 오류 메시지 대신 오류 코드를 가져 오는 방법이 있습니까? 앞에서 설명한 것처럼 상태 코드가 5 (즉, 500,503)로 시작하는 모든 오류를 catch해야합니다. –

+0

오류 개체에는 원하는 모든 정보가 들어 있습니다. 내 대답을 지금 바로 업데이트 할게 – Dane

+0

지금이 오류가 발생했습니다 '예상치 못한 오류가 발생했습니다 TypeError : '상태'가 'unvalued at eval'에서 읽을 수 있습니다. –