我尝试使用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尝试一下。
基于Kim Kern解决方案,我创建了这个抽象类
export abstract class AbstractErrorInterceptor<T> implements NestInterceptor {
protected interceptedType: new (...args) => T;
intercept(
context: ExecutionContext,
call$: Observable<any>,
): Observable<any> | Promise<Observable<any>> {
return call$.pipe(
catchError(exception => {
if (exception instanceof this.interceptedType) {
this.handleError(exception);
}
throw exception;
}),
);
}
abstract handleError(exception: T);
}
还有一些实现
export class EntityNotFoundFilter extends AbstractErrorInterceptor<EntityNotFoundError> {
interceptedType = EntityNotFoundError;
handleError(exception: EntityNotFoundError) {
throw new NotFoundException(exception.message);
}
}
您正在创建自己的基于HTTP的异常类的版本,这已经与NestJS一起提供,这似乎很奇怪。默认情况下,这些将自动转换为具有正确错误代码的HTTP响应。你正在增加拦截器和抽象类实现的开销,而你可以抛出NestJS错误并免费获得它。这是您所指的内置机制。
throw new BadRequestException('you done goofed');
结果是:
{"statusCode":400,"error":"Bad Request","message":"you done goofed"}