使用 koa.js + axios 获取错误消息
Getting error message with koa.js + axios
我在前端使用 koa.js for back-end and axios 进行 http 请求。我想在 koa.js 中设置错误消息并在前端获取错误消息,但我只收到默认错误消息 "Request failed with status code 500"
koa.jsapi来电
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//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
函数抛出数组而不是错误对象。在您的屏幕截图上,错误是 [{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
.
我在前端使用 koa.js for back-end and axios 进行 http 请求。我想在 koa.js 中设置错误消息并在前端获取错误消息,但我只收到默认错误消息 "Request failed with status code 500"
koa.jsapi来电
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//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
函数抛出数组而不是错误对象。在您的屏幕截图上,错误是 [{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
.