我在前端使用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);
});
};
}

发布于 2017-12-05 20:40:27
1) 主要问题 compileOneInterest函数抛出数组代替错误对象。在你的截图上错误的是[{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。
https://stackoverflow.com/questions/47595754
复制相似问题