Skip to Content
BackendNestJs29-exception-filter

1. Exception Filter 소개

nestjs-request-life-cycle

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

Filter_1


1.1 Exception Filter 구현방법

typescript
1
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common'
2
import { Request, Response } from 'express'
3
4
@Catch(HttpException)
5
export class HttpExceptionFilter implements ExceptionFilter {
6
catch(exception: HttpException, host: ArgumentsHost) {
7
const ctx = host.switchToHttp()
8
const response = ctx.getResponse<Response>()
9
const request = ctx.getRequest<Request>()
10
const status = exception.getStatus()
11
12
response.status(status).json({
13
statusCode: status,
14
message: exception.message,
15
timestamp: new Date().toLocaleString('kr'),
16
})
17
}
18
}

2. HttpExceptionFilter 만들기

common/exception-filter/http.exception-filter.ts 파일을 만든다.

common/exception-filter/http.exception-filter.ts
1
import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common'
2
3
@Catch(HttpException)
4
export class HttpExceptionFilter implements ExceptionFilter {
5
catch(exception: HttpException, host: ArgumentsHost) {
6
const ctx = host.switchToHttp()
7
const response = ctx.getResponse()
8
const request = ctx.getRequest()
9
const status = exception.getStatus()
10
11
/**** Filter 전역 설정
12
* 로그 파일을 생성하거나,
13
* 에러 모니터링 시스템에 API 요청하기 기능을 만들고
14
* global하게 쓸 수도 있음(main.ts)
15
*/
16
17
response.status(status).json({
18
statusCode: status,
19
message: exception.message,
20
timestamp: new Date().toLocaleString('kr'),
21
path: request.url,
22
})
23
}
24
}

이제 작성한 Filter를 posts 컨틀로러에 getPosts에 적용해본다.

posts.controller.ts
1
// posts.controller.ts 생략
2
/*** 1) GET /posts
3
* 모든 post를 다 가져온다
4
*/
5
@Get()
6
@UseInterceptors(LogInterceptor)
7
@UseFilters(HttpExceptionFilter)
8
getPosts(@Query() query: PaginatePostDto) {
9
throw new BadRequestException('에러 테스트')
10
return 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
// 생략
2
async function bootstrap() {
3
// 생략
4
app.useGlobalFilters(new HttpExceptionFilter()) // 주석 처리
5
await app.listen(3000)
6
}
7
bootstrap()