2017-12-01 48 views
0

백엔드에 koa.js, 프런트 엔드에 http 요청에 axios을 사용하고 있습니다. 나는 koa.js에서 오류 메시지를 설정하고 프런트 엔드에서 오류 메시지 싶지만 koa.js + axios로 오류 메시지 받기

koa.js API 호출 "요청은 상태 코드 500로 실패"단지 기본 오류 메시지가

Axios의와
module.exports.addIntr = async (ctx, next) => { 
    const intrObj = ctx.request.body; 
    try { 
    intrObj = await compileOneInterest(intrObj); 
    ctx.response.body = intrObj; 
    } catch (err) { 
    const statusCode = err.status || 500; 
    ctx.throw(statusCode, err.message); 
    } 
}; 

enter image description here

HTTP 요청

export function addInter(interObj) { 
    return (dispatch) => { 
    const url = `${API_ADDRESS}/ep/${10}/intr/`; 

    axios({ 
     method: 'post', 
     url, 
     data: interObj, 
     // params: { 
     // auth: AccessStore.getToken(), 
     // }, 
    }) 
     .then((response) => { 
     dispatch(addIntrSuccess(response.data)); 
     }) 
     .catch((error) => { 
     dispatch(handlePoiError(error.message)); 
     console.log(error.response); 
     console.log(error.request); 
     console.log(error.message); 
     }); 
    }; 
} 
,

enter image description here

답변

1

1) 주요 문제compileOneInterest 함수 배열 대신 오류 오브젝트. 스크린 샷의 오류는 [{message: 'Sorry, that page does not exist', code: 34}]입니다. 시도 블록이 실행 중입니다 :

const statusCode = err.status || 500; // undefined || 500 
ctx.throw(statusCode, err.message); // ctx.throw(500, undefined); 

기본 메시지가 표시됩니다.

2)에 오류가 같은 개체를 사용하는 대신 new Error('message') 또는 CustomError('message', 34)

class CustomError extends Error { 
    constructor(message, code) { 
    super(message); 
    this.code = code; 
    } 
} 

모범 사례는 오류 또는 사용자 정의 오류 객체를 던져.

3) 귀하의 statusCode 계산은 err.status 대신 err.code을 사용합니다.

+0

위대한 답변, 고맙습니다. – Matt