Em chào mọi ngưởi, em có tham khảo cách viết nodejs bằng typescript. Em bị một vấn đề là khi em return next(error) thì nó kh chạy vào cái middleware handle error của em nó throw ra lỗi trên console. Mong mọi người giúp em phần này với ạ
useHandlerError.ts:
import { Request, Response } from 'express';
export class ErrorResponse extends Error {
public statusCode: number;
constructor(message: string, statusCode: number) {
super(message);
this.statusCode = statusCode;
}
}
const handleError = (err: any, req: Request, res: Response) => {
res.status(err.statusCode || 500).json({
success: false,
error: err.message || 'Internal Server Error',
});
};
export default handleError;
category.controller.ts:
import { NextFunction, Request, Response } from 'express';
import { createCategory } from '../services/category.service';
import { ErrorResponse } from '../middlewares/error';
export const handleCreateCategory = async (
req: Request,
res: Response,
next: NextFunction
) => {
// const category = await createCategory(req.body);
// return res.status(200).send(category);
return next(new ErrorResponse('cccca 3000', 401));
};
app.ts:
import express, { Express, Response, Request } from 'express';
import {
authRouter,
productRouter,
categoryRouter,
cartRouter,
} from './routes';
import { useErrorHandler } from './middlewares';
class App {
public express: Express;
private readonly ENDPOINT: string;
constructor() {
this.express = express();
this.ENDPOINT = '/api/v1';
this.setHeaders();
this.setMiddlewares();
this.mountRoutes();
}
private setHeaders(): void {}
private setMiddlewares(): void {
this.express.use(express.json());
this.express.use(express.urlencoded());
}
private mountRoutes(): void {
this.express.use(`${this.ENDPOINT}/auth`, authRouter);
this.express.use(`${this.ENDPOINT}/product`, productRouter);
this.express.use(`${this.ENDPOINT}/category`, categoryRouter);
this.express.use(`${this.ENDPOINT}/cart`, cartRouter);
//handle err
this.express.use(useErrorHandler);
}
}
export default new App().express;
Throw error: