Хочу понять порядок глобальных ExceptionFilter в NestJS
У меня есть несколько глобальных ExceptionFilter. Http and All. Я хочу сначала ловить HttpException. А через All ловить другие ошибки
http-exception.filter.ts
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
Logger,
} from '@nestjs/common';
import { Response } from 'express';
import * as Sentry from '@sentry/node';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const exceptionResponse = exception.getResponse();
const status = exception.getStatus();
const logger = new Logger('HttpExceptionFilter');
const stack = exception.stack || '';
// TODO LOG and catch HttpStatus.INTERNAL_SERVER_ERROR and send notifications to slack
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const messages = exception.getResponse().message || exception.message;
// if (typeof messages === 'string') messages = [messages];
logger.error(`Status error: ${status}`);
logger.error(
{
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
error: exception.code || 0,
messages,
},
stack,
);
try {
Sentry.captureException(exception);
} catch (error) {
logger.error(`Error send errors Sentry`);
}
response.status(status).json({
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
error: exception.code || 0,
messages,
});
}
}
all-exaptions.filter.ts
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
HttpStatus,
Logger,
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import * as Sentry from '@sentry/node';
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
constructor(private readonly httpAdapterHost: HttpAdapterHost) {}
catch(exception: unknown, host: ArgumentsHost): void {
// In certain situations `httpAdapter` might not be available in the
// constructor method, thus we should resolve it here.
const { httpAdapter } = this.httpAdapterHost;
const ctx = host.switchToHttp();
const logger = new Logger('AllExceptionsFilter');
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const stack = exception.stack || '';
const httpStatus =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const messages = exception.message || '';
logger.error(`Status error: ${httpStatus}`);
logger.error(
{
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
error: exception?.code || 0,
messages,
},
stack,
);
try {
Sentry.captureException(exception);
} catch (error) {
logger.error(`Error send errors Sentry`);
}
const responseBody = {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
error: exception.code || 0,
messages,
};
httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);
}
}
Но all-exaptions.filter.ts перехватывает все ошибки до http-exception.filter.ts
В коде он даже перехватывает ошибки до try {} catch
например
matches.service.ts
async matchesGet(req: ExpressRequestInterface): Promise<MatchesClass> {
throw new Error('Test');
const gameId: mongoose.Types.ObjectId = req.user.games[0];
...
прям тут и отлавливает а должен в контролере у меня там стоит try catc
matches.controler.ts
async matchesGet(
@Req() req: ExpressRequestInterface,
@Query() paginationQuery: PaginationQueryDto,
) {
try {
return this.matchesService.matchesGet(req);
} catch (error) {
if (error instanceof ValidationError) {
throw error;
} else {
const newError = new HttpException(
error,
HttpStatus.INTERNAL_SERVER_ERROR,
);
newError.stack += `CAUSED BY:` + newError.stack;
throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
как сделать чтобы все работало чотко по порядку? Зарегестрированы глобально они в проекти вот так
app.module.ts
providers: [
{
provide: APP_FILTER,
useClass: AllExceptionsFilter,
},
{
provide: APP_FILTER,
useClass: HttpExceptionFilter,
},
AppService, ], })
---
порядок тут менял не помогло