
Exception Filter란?
Exception Filter는 NestJS에서 발생하는 예외를 잡아내어 일관된 에러 응답을 제공하는 메커니즘이다.
주요 기능
- 예외 포착 및 변환
- 컨트롤러나 서비스, 심지어 인터셉터 등에서 발생한 예외를 잡아내어, 클라이언트에게 적절한 응답 형태로 변환해 준다.
- @Catch() 데코레이터를 사용해 특정 예외 타입 또는 모든 예외를 대상으로 설정할 수 있다.
- 응답 커스터마이징
- 예외 발생 시, HTTP 상태 코드, 에러 메시지, 타임스탬프, 요청 URL 등 추가 정보를 응답에 포함할 수 있다.
- 플리케이션 전반의 에러 핸들링 정책을 통일할 때 유용하다.
- 글로벌 또는 개별 적용
- Exception Filter는 전역(Global)으로 등록하거나, 특정 컨트롤러나 핸들러에 국한시켜 적용할 수 있다.
HttpException Filter 만들기
import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from "@nestjs/common"; @Catch(HttpException) export class HttpExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const request = ctx.getRequest(); const status = exception.getStatus(); const res = exception.getResponse(); const error = typeof res === 'object' && (res as any).error ? (res as any).error : exception.message; const message = typeof res === 'object' && (res as any).message ? (res as any).message : exception.message; response.status(status).json({ statusCode: status, error, // 예: "Bad Request" message, // 예: "테스트" timeStamp: new Date().toLocaleString('kr'), path: request.url, }); } }
위와 같이 구현하면 HttpException에 관한 예외를 낚아채 변형하여 응답할 수 있다.
적용하기
// 1) GET /posts // 모든 posts를 가져온다 @Get() @UseInterceptors(LogInterceptor) @UseFilters(HttpExceptionFilter) getPosts( @Query() query: PaginatePostDto, ) { throw new BadRequestException('테스트'); return this.postsService.paginatePosts(query); }
결과


글로벌하게 적용하기
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { ValidationPipe } from '@nestjs/common'; import { HttpExceptionFilter } from './common/exception-filter/http.exception-filter'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalPipes(new ValidationPipe({ transform: true, transformOptions: { enableImplicitConversion: true, }, whitelist: true, forbidNonWhitelisted: true, })); app.useGlobalFilters(new HttpExceptionFilter()); await app.listen(process.env.PORT ?? 3000); } bootstrap();
app.useGlobalFilters(new HttpExceptionFilter());
main.ts에 위와 같이 글로벌하게 적용하면 어느 로직에서든 HttpException 에러가 발생할 때 실행시킬 수 있게 된다.
HttpExceptionFilter 내에 로그를 저장하는 기능이 있다면 유용하게 사용될 수 있다.
'NestJS' 카테고리의 다른 글
[NestJS] SocketIO 일반 (0) | 2025.03.12 |
---|---|
[NestJS] Middleware (0) | 2025.03.11 |
[NestJS] Interceptor (0) | 2025.03.10 |
[NestJS] Transaction (0) | 2025.03.10 |
[NestJS] 파일 업로드 (선 업로드 방식) (0) | 2025.03.07 |