浏览代码

simplify error handling

Richard Köhl 2 年之前
父节点
当前提交
019485902c
共有 2 个文件被更改,包括 22 次插入17 次删除
  1. 20 15
      src/interfaces/controllers/errors.controller.ts
  2. 2 2
      src/interfaces/router.ts

+ 20 - 15
src/interfaces/controllers/errors.controller.ts

@@ -3,20 +3,25 @@ import { HTTPStatus } from 'deps';
 import { logger } from 'infra/logger.ts';
 import Controller from 'if/controllers/controller.class.ts';
 
+const NotFoundController = new Controller({
+  '*_*': (req: Request) => {
+    return Controller.response(req, 'not found', {
+      status: HTTPStatus.NotFound,
+    });
+  },
+});
+
+const InternalServerErrorController = new Controller({
+  '*_*': (req: Request, error?: string) => {
+    logger.error(error);
+    return Controller.response(req, 'internal server error', {
+      status: HTTPStatus.InternalServerError,
+    });
+  },
+});
+
 export const ControllerErrors = {
-  NotFound: new Controller({
-    '*_*': (req: Request) => {
-      return Controller.response(req, 'not found', {
-        status: HTTPStatus.NotFound,
-      });
-    },
-  }),
-  InternalServerError: new Controller({
-    '*_*': (req: Request, error?: string) => {
-      logger.error(error);
-      return Controller.response(req, 'internal server error', {
-        status: HTTPStatus.InternalServerError,
-      });
-    },
-  }),
+  NotFound: (req: Request) => NotFoundController.handlers['*_*'](req),
+  InternalServerError: (req: Request, error?: string) =>
+    InternalServerErrorController.handlers['*_*'](req, error),
 };

+ 2 - 2
src/interfaces/router.ts

@@ -19,11 +19,11 @@ export const router = (req: Request) => {
       return handler(req, undefined, { 'Content-Type': 'application/json' });
     } else {
       // Use the handler from the NotFound controller
-      return ControllerErrors.NotFound.handlers['*_*'](req);
+      return ControllerErrors.NotFound(req);
     }
   } catch (error: unknown) {
     // Use the handler from the InternalServerError controller
-    return ControllerErrors.InternalServerError.handlers['*_*'](
+    return ControllerErrors.InternalServerError(
       req,
       error instanceof Error ? error.message : 'unknown error!',
     );