【发布时间】:2021-09-03 18:15:44
【问题描述】:
我有一个自定义的常规错误响应,它会在执行 return next(error) 时运行,但它不起作用,它向控制台抛出了一个错误。请帮助我并给我一个解释。
useErrorHandler.ts:这是我的自定义错误响应扩展 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:这是我的控制器,我试图给出错误
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;
【问题讨论】:
-
handleError函数必须有 4 个参数,以便快速将其识别为错误处理程序。 Docs ...错误处理函数有四个参数,而不是三个:(err, req, res, next)。 -
@Molda 我解决了,谢谢
标签: node.js typescript express