From ba65c1fe83170e1dfa1ef03edd10eaa6288ea8d4 Mon Sep 17 00:00:00 2001 From: Methapon2001 <61303214+Methapon2001@users.noreply.github.com> Date: Tue, 2 Apr 2024 15:26:37 +0700 Subject: [PATCH] refactor: add devMessage field (useful in front-end) --- src/app.ts | 8 ++++++++ src/interfaces/http-error.ts | 4 +++- src/middlewares/error.ts | 3 +++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/app.ts b/src/app.ts index e7b19d2..2d500f5 100644 --- a/src/app.ts +++ b/src/app.ts @@ -20,6 +20,14 @@ const APP_PORT = +(process.env.APP_PORT || 3000); RegisterRoutes(app); + app.get("*", (_, res) => + res.status(404).send({ + status: 404, + message: "Route not found.", + devMessage: "unknown_url", + }), + ); + app.use(error); app.listen(APP_PORT, APP_HOST, () => console.log(`Listening on: http://localhost:${APP_PORT}`)); diff --git a/src/interfaces/http-error.ts b/src/interfaces/http-error.ts index 5d396e2..8abe48b 100644 --- a/src/interfaces/http-error.ts +++ b/src/interfaces/http-error.ts @@ -6,13 +6,15 @@ class HttpError extends Error { */ status: HttpStatus; message: string; + devMessage?: string; - constructor(status: HttpStatus, message: string) { + constructor(status: HttpStatus, message: string, devMessage?: string) { super(message); this.name = "HttpError"; this.status = status; this.message = message; + this.devMessage = devMessage; } } diff --git a/src/middlewares/error.ts b/src/middlewares/error.ts index b010f0a..d80ceb3 100644 --- a/src/middlewares/error.ts +++ b/src/middlewares/error.ts @@ -8,6 +8,7 @@ function error(error: Error, _req: Request, res: Response, _next: NextFunction) return res.status(error.status).json({ status: error.status, message: error.message, + devMessage: error.devMessage, }); } @@ -16,6 +17,7 @@ function error(error: Error, _req: Request, res: Response, _next: NextFunction) status: HttpStatus.UNPROCESSABLE_ENTITY, message: "Validation error(s).", detail: error.fields, + devMessage: "missing_or_invalid_parameter", }); } @@ -24,6 +26,7 @@ function error(error: Error, _req: Request, res: Response, _next: NextFunction) return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ status: HttpStatus.INTERNAL_SERVER_ERROR, message: error.message, + devMessage: "system_error", }); }