Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: handle server errors in api #66

Merged
merged 2 commits into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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";