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;
}
}));
}
}
Попробуйте это в этом коде и ящике .