Files
buy-lite/server/app/middleware/errorHandler.js

20 lines
629 B
JavaScript
Raw Normal View History

2022-12-30 16:03:32 +08:00
module.exports = () => async function errorHandler(ctx, next) {
try {
await next();
} catch (err) {
ctx.app.emit('error', err, ctx);
const status = err.status || 500;
// 生产环境时 500 错误的详细错误内容不返回给客户端,因为可能包含敏感信息
const error =
status === 500 && ctx.app.config.env === 'prod'
? 'Internal Server Error'
: err.message;
// 从 error 对象上读出各个属性,设置到响应中
2022-12-30 16:34:57 +08:00
ctx.body = {code: 1, error};
2022-12-30 16:03:32 +08:00
if (status === 422) {
ctx.body.detail = err.errors;
}
ctx.status = status;
}
}