如何在nestjs上捕获中间件中的错误

问题描述 投票:0回答:2

我正在尝试使用中间件中的 try-catch 结构捕获错误。我在 try 块中调用下一个函数,如果出现空引用等错误,我会等待在 catch 块中捕获错误。但它不起作用。

export function GlobalMiddleware(req: Request, res: Response, next: NextFunction) {
 
 try {
    next();
 } catch (error) {
    console.log(error);
 }

}
error-handling nestjs
2个回答
3
投票

根据文档,可以使用异常过滤器捕获所有未处理的异常。

您可以在文档中了解有关如何使用全局异常过滤器的更多信息,因为有一个相关部分:https://docs.nestjs.com/exception-filters#catch-everything


0
投票

as this github comment 也许这对你有用(对我有用):

export function GlobalMiddleware(req: Request, res: Response, next: NextFunction) {
 
 try {
    next();
 } catch (error) {
    console.log(error);
    next(error);
 }

}
© www.soinside.com 2019 - 2024. All rights reserved.