gpt4 book ai didi

javascript - NestJS 从 ExceptionFilter 抛出

转载 作者:搜寻专家 更新时间:2023-10-30 21:18:41 25 4
gpt4 key购买 nike

我尝试使用 ExceptionFilter 将异常映射到对应的 HTTP。

这是我的代码:

@Catch(EntityNotFoundError)
export class EntityNotFoundFilter implements ExceptionFilter {
catch(exception: EntityNotFoundError, _host: ArgumentsHost) {
throw new NotFoundException(exception.message);
}
}

但是,当过滤器代码被执行时,我得到了一个UnhandledPromiseRejectionWarning

 (node:3065) UnhandledPromiseRejectionWarning: Error: [object Object]
at EntityNotFoundFilter.catch ([...]/errors.ts:32:15)
at ExceptionsHandler.invokeCustomFilters ([...]/node_modules/@nestjs/core/exceptions/exceptions-handler.js:49:26)
at ExceptionsHandler.next ([...]/node_modules/@nestjs/core/exceptions/exceptions-handler.js:13:18)
at [...]/node_modules/@nestjs/core/router/router-proxy.js:12:35
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:182:7)
(node:3065) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 5)

我该如何解决这个问题?

最佳答案

ExceptionFilter总是在发送响应之前被调用的最后一个地方,它负责构建响应。您不能从 ExceptionFilter 中重新抛出异常。

@Catch(EntityNotFoundError)
export class EntityNotFoundFilter implements ExceptionFilter {
catch(exception: EntityNotFoundError, host: ArgumentsHost) {
const response = host.switchToHttp().getResponse();
response.status(404).json({ message: exception.message });
}
}

或者,您可以创建一个 Interceptor改变你的错误:

@Injectable()
export class NotFoundInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
// next.handle() is an Observable of the controller's result value
return next.handle()
.pipe(catchError(error => {
if (error instanceof EntityNotFoundError) {
throw new NotFoundException(error.message);
} else {
throw error;
}
}));
}
}

在这个 codesandbox 中尝试一下.

关于javascript - NestJS 从 ExceptionFilter 抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54945917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com