diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 458f6dd..9da4dc6 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -5,6 +5,7 @@ import { ILogger } from "@zkchainhub/shared"; import { listRoutes, setupOpenApiConfiguration as setupOpenApi } from "./api-docs/index.js"; import { ConfigType } from "./common/config/index.js"; +import { generalErrorHandler } from "./common/middleware/generalError.middleware.js"; import { requestLogger } from "./common/middleware/requestLogger.middleware.js"; import { zodErrorHandler } from "./common/middleware/zodError.middleware.js"; import { BaseRouter } from "./common/routes/baseRouter.js"; @@ -64,5 +65,6 @@ export class App { private initializeErrorHandling(): void { this.app.use(zodErrorHandler); + this.app.use(generalErrorHandler); } } diff --git a/apps/api/src/common/middleware/cache.middleware.ts b/apps/api/src/common/middleware/cache.middleware.ts index c6fec22..c7e87e9 100644 --- a/apps/api/src/common/middleware/cache.middleware.ts +++ b/apps/api/src/common/middleware/cache.middleware.ts @@ -22,10 +22,11 @@ export function cacheMiddleware(args: { ttl: number } = { ttl: DEFAULT_TTL }) { // Store the original send and json functions const originalJson = res.json.bind(res); // Override the json function - res.json = (body): Response => { - // Cache the response body - cache.set(key, body, args.ttl); + if (!("errors" in body)) { + // Cache the response body if it is not an error response + cache.set(key, body, args.ttl); + } // Call the original json function with the response body return originalJson(body); }; diff --git a/apps/api/src/common/middleware/generalError.middleware.ts b/apps/api/src/common/middleware/generalError.middleware.ts new file mode 100644 index 0000000..795e447 --- /dev/null +++ b/apps/api/src/common/middleware/generalError.middleware.ts @@ -0,0 +1,14 @@ +import { isNativeError } from "util/types"; +import { NextFunction, Request, Response } from "express"; + +export const generalErrorHandler = ( + err: unknown, + req: Request, + res: Response, + _next: NextFunction, +) => { + return res.status(500).json({ + message: "Internal server error", + errors: isNativeError(err) ? err.message : err, + }); +}; diff --git a/apps/api/src/common/middleware/index.ts b/apps/api/src/common/middleware/index.ts index ed86ec0..c82314b 100644 --- a/apps/api/src/common/middleware/index.ts +++ b/apps/api/src/common/middleware/index.ts @@ -1,2 +1,3 @@ export * from "./zodError.middleware.js"; export * from "./requestLogger.middleware.js"; +export * from "./generalError.middleware.js";