27 lines
861 B
JavaScript
27 lines
861 B
JavaScript
"use strict";
|
|
|
|
module.exports = (option, app) => {
|
|
return async function(ctx, next) {
|
|
try {
|
|
await next();
|
|
} catch (err) {
|
|
// 所有的异常都在 app 上触发一个 error 事件,框架会记录一条错误日志
|
|
app.emit("error", err, this);
|
|
const status = err.status || 500;
|
|
// 生产环境时 500 错误的详细错误内容不返回给客户端,因为可能包含敏感信息
|
|
const error =
|
|
status === 500 && app.config.env === "prod"
|
|
? "服务器错误"
|
|
: err.message;
|
|
// 从 error 对象上读出各个属性,设置到响应中
|
|
if (status == 401) {
|
|
ctx.status = 200;
|
|
ctx.body = { code: 40001, message: "token缺少或者已经过期" };
|
|
} else {
|
|
ctx.status = status;
|
|
ctx.body = { code: status, error };
|
|
}
|
|
}
|
|
};
|
|
};
|