[英]Getting error message with koa.js + axios
我正在將koa.js用於后端,將axios用於前端的HTTP請求。 我想在koa.js中設置錯誤消息,並在前端獲取錯誤消息,但是我僅收到默認錯誤消息“請求失敗,狀態碼為500”
koa.js api調用
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);
}
};
帶有axios的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);
});
};
}
1) 主要問題 compileOneInterest
函數將引發數組而不是Error對象。 在您的屏幕截圖上,錯誤是[{message: 'Sorry, that page does not exist', code: 34}]
。 您的try塊正在運行:
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.