intermediate

NestJS filters

Преобразуйте framework, HTTP, validation и domain exceptions в consistent responses с достаточным operational context.

Exception filters перехватывают thrown exceptions и мапят в HTTP responses. `@Catch()` задаёт типы exceptions для filter. Global filter в `main.ts` — единый error shape.

					@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const res = ctx.getResponse<Response>();
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    const body =
      exception instanceof HttpException
        ? exception.getResponse()
        : { message: 'Internal server error' };
    res.status(status).json(body);
  }
}
				

Domain exceptions расширяют `HttpException` или мапятся в custom filter. Filters после guards, interceptors и pipes — последняя линия shaping response при сбое.

На интервью: filters vs Express error middleware, логирование в filters vs interceptors, correlation IDs.

Типовые ошибки: всё как 500, утечка stack traces, разные error shapes без global filter.

Компромисс — между простотой, производительностью, безопасностью и эксплуатацией: назовите, что оптимизировали и какую цену приняли.

Чеклист:

  • Global exception filter.
  • Domain errors → HTTP status.
  • Лог server errors с контекстом; санитизация клиенту.
  • @Catch для специализированных exception types.