on
NestJs Error Handling
NestJs Error Handling
NestJs에는 애플리케이션 전체의 모든 예외 처리를 하는 exceptions layer가 내장되어 있습니다.
애플리케이션 코드에서 예외 처리를 하지 않으면 이 레이어에서 예외를 처리한다.
커스텀으로 예외 레이어를 만들지 않는다면 아래와 같이 기본 JSON 응답을 합니다.
{ "statusCode": 500, "message": "Internal server error" }
Exception Filters
기본 예외 필터가 자동으로 많은 경우의 예외 처리를 해주지만 Custom으로 완전 제어를 하고 싶은 경우가 있습니다.
예를 들어 로깅을 추가하거나 다른 형태의 JSON 스키마로 반환할 수도 있습니다.
http-exception.filter.ts
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common'; import { Request, Response } from 'express'; /* @Catch(HttpException)은 http통신의 예외를 캐치하겠다는 뜻입니다. 만약 모든 예외를 캐치하고 싶다면 @Catch()로 적용하시면 됩니다. */ @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(); response .status(status) .json({ statusCode: status, timestamp: new Date().toISOString(), path: request.url, }); } }
로깅을 적용하는 방법은 지난 글에 작성해두었습니다.
2021.08.30 - [BackEnd/NestJS] - NestJs에 Winston 도입하기
Usage
이제 위에서 만든 exception filter를 적용해보겠습니다.
@UseFilters(AllExceptionFilter) @Controller('user') export class UserController { constructor(private userService: UsersService) {} // ... }
exception filter를 적용하고 싶다면 @UseFilters()를 import해야 합니다. ( 이름이 아주 직관적이죠? )
user 컨트롤러의 라우팅 핸들러 전체에 exception filter를 적용하고 싶다면 @Controller()에 위와 같이 적용하시면 됩니다.
그리고 특정 라우팅 핸들러에만 적용하고 싶다면
@Controller('user') export class UserController { constructor(private userService: UsersService) {} @UseFilters(AllExceptionFilter) @Get() // ... async find() { // ... } // ... }
컨트롤러에 적용한 것과 비슷하게 해당 라우팅 핸들러에 위와 같이 적용하시면 됩니다.
이만 기본적인 NestJs Error handling에 대해 작성해보았습니다.
from http://bang-jh.tistory.com/13 by ccl(A) rewrite - 2021-09-05 22:00:05