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

ch-Add a global error handler middleware #26

Merged
merged 1 commit into from
Apr 26, 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
8 changes: 8 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import dotenv from "dotenv";
import router from "./routes";
import { addDocumentation } from "./startups/docs";

import {CustomError,errorHandler} from "./middlewares/errorHandler";
dotenv.config();

export const app = express();
Expand All @@ -12,11 +13,18 @@ app.use(express.json());

app.use(cors({ origin: "*" }));

app.all('*', (req: Request,res: Response,next) =>{
const error = new CustomError(`Can't find ${req.originalUrl} on the server!`,404);
error.status = 'fail';
next(error);
})

addDocumentation(app);
app.get("/api/v1", (req: Request, res: Response) => {
res.send("Knights Ecommerce API");
});
app.use(router)
app.use(errorHandler);
export const server = app.listen(port, () => {
console.log(`[server]: Server is running at http://localhost:${port}`);
})
30 changes: 30 additions & 0 deletions src/middlewares/errorHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Request, Response, NextFunction } from 'express';

class CustomError extends Error {
statusCode: number;
status: string;

constructor(message: string, statusCode: number) {
super(message);
this.statusCode = statusCode;
this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';
Error.captureStackTrace(this, this.constructor);
}
}

const errorHandler = (
err: CustomError,
req: Request,
res: Response,
next: NextFunction
) => {
err.statusCode = err.statusCode || 500;
err.status = err.status || 'error';
res.status(err.statusCode).json({
status: err.statusCode,
message: err.message
});
console.error(err.stack);
};

export { CustomError, errorHandler };