Skip to content

Commit 797992b

Browse files
committed
globalErrorHandler.ts added
1 parent 73a2213 commit 797992b

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "express-error-toolkit",
3-
"version": "1.0.0",
3+
"version": "0.1.0-beta.1",
44
"main": "index.js",
55
"scripts": {
66
"test": "echo \"Error: no test specified\" && exit 1"

src/globalErrorHandler.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { NextFunction, Request, Response } from "express";
2+
import { StatusCodes } from "http-status-toolkit";
3+
4+
interface CustomError extends Error {
5+
statusCode?: number;
6+
details?: string | null;
7+
}
8+
9+
10+
const errorHandlerMiddleware = (err: CustomError, req: Request, res: Response, next: NextFunction) => {
11+
let status = err.statusCode || StatusCodes.INTERNAL_SERVER_ERROR;
12+
let message = err.message || "Something went wrong, please try again later.";
13+
14+
const notFound = StatusCodes.NOT_FOUND
15+
16+
const errorResponse: { success: boolean; error: string; details?: string | null} = {
17+
success: false,
18+
error: message,
19+
};
20+
21+
if (err.details) {
22+
errorResponse.details = err.details;
23+
}
24+
25+
res.status(status).json(errorResponse);
26+
}
27+
28+
export default errorHandlerMiddleware;

0 commit comments

Comments
 (0)