我正在尝试使用中间件中的 try-catch 结构捕获错误。我在 try 块中调用下一个函数,如果出现空引用等错误,我会等待在 catch 块中捕获错误。但它不起作用。
export function GlobalMiddleware(req: Request, res: Response, next: NextFunction) {
try {
next();
} catch (error) {
console.log(error);
}
}
根据文档,可以使用异常过滤器捕获所有未处理的异常。
您可以在文档中了解有关如何使用全局异常过滤器的更多信息,因为有一个相关部分:https://docs.nestjs.com/exception-filters#catch-everything
as this github comment 也许这对你有用(对我有用):
export function GlobalMiddleware(req: Request, res: Response, next: NextFunction) {
try {
next();
} catch (error) {
console.log(error);
next(error);
}
}