29-exception-filter
1. Exception Filter 소개

- Exception Filter에서 수행한 부분들은 interceptor에서 추가 로직을 또 구현할 수 있다.
- Exception Filter는 말 그대로 예외를 필터링 하는 기능이다.
- NestJS에서는 자체적으로 예외 레이어를 관리한다.
- 서버에서 발생한 예외가 따로 핸들링 되지 않으면 NestJS 예외 레이어에서 에러를 사용자 친화적으로 변환해서 응답 할 수 있다
- 응답을 변형하는 부분은 사실 크게 쓸 일이 많지는 않다.
- 왜냐면은 예외라는 것 자체가 예외가 던져졌을 때,
- 던져진 의도 그대로 사용되어야 프론트엔드에서도 의미가 있는 경우가 되게 많다.
- 그래서 예외 처리를 많이 변형하는 경우는 크게 없다.
- Exception Filter가 되게 유용한 경우
- 에러가 생겼을 때 TGS 서버 내부에서 로그를 남기거나
- 아니면 모니터링 할 수 있는 시스템한테 알려주는 로직을 작성할 때

- 공식문서 : https://docs.nestjs.com/exception-filters
- 공식문서의 그림을 보면, 클라이언트 사이드에서 요청을 보내고,
- 응답을 받을 때, Filter가 적용된다는 것을 알 수 있다.
- https://docs.nestjs.com/exception-filters#built-in-http-exceptions
- 이 Exceptions들은 모두 HTTP Exceptions을 Extend를 하고 있다.
- 그래서 나중에 Exception 필터 클래스를 만들 때,
- HTTP Exceptions에 해당되는 Exceptions들만 잡는 Exception 필터를 만듭니다.
1.1 Exception Filter 구현방법
typescript
1import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common'2import { Request, Response } from 'express'34@Catch(HttpException)5export class HttpExceptionFilter implements ExceptionFilter {6catch(exception: HttpException, host: ArgumentsHost) {7const ctx = host.switchToHttp()8const response = ctx.getResponse<Response>()9const request = ctx.getRequest<Request>()10const status = exception.getStatus()1112response.status(status).json({13statusCode: status,14message: exception.message,15timestamp: new Date().toLocaleString('kr'),16})17}18}
2. HttpExceptionFilter 만들기
common/exception-filter/http.exception-filter.ts 파일을 만든다.
common/exception-filter/http.exception-filter.ts
1import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common'23@Catch(HttpException)4export class HttpExceptionFilter implements ExceptionFilter {5catch(exception: HttpException, host: ArgumentsHost) {6const ctx = host.switchToHttp()7const response = ctx.getResponse()8const request = ctx.getRequest()9const status = exception.getStatus()1011/**** Filter 전역 설정12* 로그 파일을 생성하거나,13* 에러 모니터링 시스템에 API 요청하기 기능을 만들고14* global하게 쓸 수도 있음(main.ts)15*/1617response.status(status).json({18statusCode: status,19message: exception.message,20timestamp: new Date().toLocaleString('kr'),21path: request.url,22})23}24}
이제 작성한 Filter를 posts 컨틀로러에 getPosts에 적용해본다.
posts.controller.ts
1// posts.controller.ts 생략2/*** 1) GET /posts3* 모든 post를 다 가져온다4*/5@Get()6@UseInterceptors(LogInterceptor)7@UseFilters(HttpExceptionFilter)8getPosts(@Query() query: PaginatePostDto) {9throw new BadRequestException('에러 테스트')10return this.postsService.paginatePosts(query)11}
이제 일부러 에러를 내면, 우리가 정의한대로 응답이 온 것을 확인할 수 있다.
json
1{2"statusCode": 400,3"message": "에러 테스트",4"timestamp": "2024. 1. 7. 오후 5:44:51",5"path": "/posts?order__createdAt=DESC&take=5"6}
참고로 main.ts에서 Filter를 글로벌하게 적용할 수 있다.
- 이렇게 하면 앱 전체에서 nhttp exception 관련된 모든 exception이 발생을 할 때마다,
- 로그 모니터링 할 수 있는 로직을 작성을 했다고 가정을 했을 때,
- 에러가 날 때마다 모든 에러들에 대해서 전부 http exception 필터를 실행을 해줄 수가 있다.
- 지금은 글로벌하게 그닥 쓸 필요가 없으니까, 일단은 주석 처리한다.
main.ts
1// 생략2async function bootstrap() {3// 생략4app.useGlobalFilters(new HttpExceptionFilter()) // 주석 처리5await app.listen(3000)6}7bootstrap()