Skip to content

Commit

Permalink
feat: handle server errors in api
Browse files Browse the repository at this point in the history
  • Loading branch information
0xnigir1 committed Sep 10, 2024
1 parent 9a13844 commit 5f36711
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 3 deletions.
2 changes: 2 additions & 0 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -64,5 +65,6 @@ export class App {

private initializeErrorHandling(): void {
this.app.use(zodErrorHandler);
this.app.use(generalErrorHandler);
}
}
7 changes: 4 additions & 3 deletions apps/api/src/common/middleware/cache.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
};
Expand Down
14 changes: 14 additions & 0 deletions apps/api/src/common/middleware/generalError.middleware.ts
Original file line number Diff line number Diff line change
@@ -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,
});
};
1 change: 1 addition & 0 deletions apps/api/src/common/middleware/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from "./zodError.middleware.js";
export * from "./requestLogger.middleware.js";
export * from "./generalError.middleware.js";

0 comments on commit 5f36711

Please sign in to comment.