Browse Source

启用自定义错误过滤器

lrf 1 năm trước cách đây
mục cha
commit
38f0dd9bff
2 tập tin đã thay đổi với 17 bổ sung1 xóa
  1. 2 1
      src/configuration.ts
  2. 15 0
      src/filter/customError.filter.ts

+ 2 - 1
src/configuration.ts

@@ -10,7 +10,7 @@ import { ServiceError, FrameworkErrorEnum } from './error/service.error';
 import { IMidwayContainer, Inject, MidwayConfigService } from '@midwayjs/core';
 import * as upload from '@midwayjs/upload';
 import { UseFile } from './entity/useFile.entity';
-
+import { CustomErrorFilter } from './filter/customError.filter';
 
 const axiosResponse = response => {
   if (response.status === 200) return response.data;
@@ -70,6 +70,7 @@ export class FreeConfiguration {
   async onReady(container: IMidwayContainer) {
     // TODO something
     this.app.getMiddleware().insertLast(ResponseMiddleware);
+    this.app.useFilter([CustomErrorFilter])
     // typegoose设置
     Typegoose.setGlobalOptions({
       schemaOptions: {

+ 15 - 0
src/filter/customError.filter.ts

@@ -0,0 +1,15 @@
+import { Catch } from '@midwayjs/core';
+import { Context } from '@midwayjs/koa';
+import { ServiceError } from '../error/service.error';
+
+@Catch(ServiceError)
+export class CustomErrorFilter {
+  async catch(err: Error, ctx: Context) {
+    // 所有的未分类错误会到这里
+    return {
+      errcode: err['code'],
+      errmsg: err.message,
+      details: err.stack,
+    };
+  }
+}