1. import { Provide, Config } from '@midwayjs/decorator';
    2. import { IWebMiddleware, IMidwayWebNext } from '@midwayjs/web';
    3. import { Context } from 'egg';
    4. import { TypeORMError } from 'typeorm';
    5. import { nok } from '../utils/res';
    6. import APIError from '../error/APIError';
    7. @Provide()
    8. export class ApiErrorMiddleware implements IWebMiddleware {
    9. @Config()
    10. isProd: boolean;
    11. resolve() {
    12. return async (ctx: Context, next: IMidwayWebNext) => {
    13. try {
    14. await next();
    15. } catch (error) {
    16. console.info('---------- 全局异常捕获 ----------');
    17. console.error(error);
    18. const { message = '程序异常' } = error;
    19. let { stack } = error;
    20. if (this.isProd) {
    21. // 正式环境不要显示 堆栈信息
    22. stack = undefined;
    23. } else {
    24. if (stack?.split) {
    25. // 分行,方便查看
    26. stack = stack.split('\n');
    27. }
    28. }
    29. if (error instanceof APIError) {
    30. return (ctx.body = nok(message, stack, error.code));
    31. }
    32. if (error instanceof TypeORMError) {
    33. return (ctx.body = nok('数据操作错误', stack, 500));
    34. }
    35. ctx.body = nok(message, stack, 500);
    36. }
    37. };
    38. }
    39. }