import { Provide, Config } from '@midwayjs/decorator';
import { IWebMiddleware, IMidwayWebNext } from '@midwayjs/web';
import { Context } from 'egg';
import { TypeORMError } from 'typeorm';
import { nok } from '../utils/res';
import APIError from '../error/APIError';
@Provide()
export class ApiErrorMiddleware implements IWebMiddleware {
@Config()
isProd: boolean;
resolve() {
return async (ctx: Context, next: IMidwayWebNext) => {
try {
await next();
} catch (error) {
console.info('---------- 全局异常捕获 ----------');
console.error(error);
const { message = '程序异常' } = error;
let { stack } = error;
if (this.isProd) {
// 正式环境不要显示 堆栈信息
stack = undefined;
} else {
if (stack?.split) {
// 分行,方便查看
stack = stack.split('\n');
}
}
if (error instanceof APIError) {
return (ctx.body = nok(message, stack, error.code));
}
if (error instanceof TypeORMError) {
return (ctx.body = nok('数据操作错误', stack, 500));
}
ctx.body = nok(message, stack, 500);
}
};
}
}