我正在使用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: '抱歉,该页面不存在', code: 34}]
。您的 try block 正在运行:
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
。
关于javascript - 使用 koa.js + axios 获取错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47595754/