From 6fe398c82a60937d15ff9fc44c0f0d525b4ccedb Mon Sep 17 00:00:00 2001 From: hippoz <10706925-hippoz@users.noreply.gitlab.com> Date: Fri, 5 Aug 2022 04:32:10 +0300 Subject: [PATCH] add custon express error handler --- src/errors.ts | 3 ++- src/server.ts | 10 +++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/errors.ts b/src/errors.ts index f660013..1d236c6 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -6,7 +6,8 @@ export const errors = { FORBIDDEN_DUE_TO_MISSING_PERMISSIONS: { code: 6005, message: "Forbidden due to missing permission(s)" }, BAD_SUPERUSER_KEY: { code: 6006, message: "Bad superuser key" }, GOT_NO_DATABASE_DATA: { code: 7001, message: "Unexpectedly got no data from database" }, - FEATURE_DISABLED: { code: 7002, message: "This feature is disabled" } + FEATURE_DISABLED: { code: 7002, message: "This feature is disabled" }, + INTERNAL_ERROR: { code: 7003, message: "Internal server error" } }; export const gatewayErrors = { diff --git a/src/server.ts b/src/server.ts index 210f5f0..84a483a 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,7 +1,8 @@ -import express, { Application, json } from "express"; +import express, { Application, ErrorRequestHandler, json } from "express"; import usersRouter from "./routes/api/v1/users"; import channelsRouter from "./routes/api/v1/channels"; import messagesRouter from "./routes/api/v1/messages"; +import { errors } from "./errors"; export default function(app: Application) { app.use(json()); @@ -9,4 +10,11 @@ export default function(app: Application) { app.use("/api/v1/channels", channelsRouter); app.use("/api/v1/messages", messagesRouter); app.use("/", express.static("frontend/public")); + + const errorHandler: ErrorRequestHandler = (error, req, res, next) => { + console.error("error: while handling request", error); + res.status(500).json({ ...errors.INTERNAL_ERROR }); + }; + + app.use(errorHandler); };