-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapiError.ts
More file actions
50 lines (44 loc) · 1.24 KB
/
apiError.ts
File metadata and controls
50 lines (44 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { Request, Response, NextFunction } from "express";
import { logger } from "./logger";
/**
* A custom error type that carries an HTTP status code.
*/
export class ApiError extends Error {
public statusCode: number;
public isOperational: boolean;
constructor(message: string, statusCode = 500, isOperational = true) {
super(message);
this.name = this.constructor.name;
this.statusCode = statusCode;
this.isOperational = isOperational;
Error.captureStackTrace(this, this.constructor);
}
}
interface ErrorResponse {
error: boolean;
message: string;
stack?: string;
}
/**
* Express middleware to catch all errors and send JSON response.
*/
export function errorHandler(
err: unknown,
req: Request,
res: Response,
next: NextFunction,
): void {
const status = err instanceof ApiError ? err.statusCode : 500;
const message =
err instanceof ApiError ? err.message : "Internal Server Error";
const responseBody: ErrorResponse = {
error: true,
message,
};
logger.error('ERROR 🔥', err);
// Include stack trace in development for debugging
if (process.env.NODE_ENV === "development" && err instanceof Error) {
responseBody.stack = err.stack;
}
res.status(status).json(responseBody);
}