Browse Source

simplify error handling

Richard Köhl 2 years ago
parent
commit
019485902c
2 changed files with 22 additions and 17 deletions
  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!',
     );