I have a custom general error response and it will run when execute return next(error), but it's not working , it threw an error to the console. Please help me and give me an explanation for this.
useErrorHandler.ts: This is my custom error response extending Error
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: This is my controller, i tried to give an error
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: this is my main file, it contains routes, headers, middlewares, etc.
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;
handleErrorfunction must have 4 arguments that is how express recognise it as an error handler. Docs ... error-handling functions have four arguments instead of three: (err, req, res, next).