[TIL] NestJS 공부 7일차

정인교·2021년 6월 10일
0

TIL(Today I Learned)

목록 보기
18/67
post-thumbnail

Exception Filter

예외 필터는 핸들링되지 않은 예외들에 대해서 반응하게 내장된 예외 레이어가 있다. 처리되지 않은 에러들을 잡아서 친숙한 응답을 제공해준다.

작동 방식

HttpException타입의 예외를 처리하는 내장된 글로벌 예외 처리기에 의해 동작한다. 만약 인식되지 않는다면 이는 HttpException의 에러가 아니거나 HttpException가 상속되지 않는 경우만 그럴 것이다.

에러 응답

{
  "statusCode": 500,
  "message": "Internal server error"
}

처리되지 않은 에러를 발견하면 위 응답을 보낸다.

표준 예외 설정

@Get()
async findAll() {
  throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
}

위 코드를 보면 throw를 이용하여 에러를 발생시켰는데, 이럴 경우 응답은

{
  "statusCode": 403,
  "message": "Forbidden"
}

아래처럼 받아진다.

에러 메세지도 포함시킬 수 있다.

코드부분

@Get()
async findAll() {
  throw new HttpException({
    status: HttpStatus.FORBIDDEN,
    error: 'This is a custom message',
  }, HttpStatus.FORBIDDEN);
}

응답부분

{
  "status": 403,
  "error": "This is a custom message"
}

예외 필터

자동적으로 많은 경우를 커버하기도하지만, 필터를 만들어 명확한 흐름의 통제와 응답 컨텐츠의 통제를 제공해줘야합니다.

커스텀한 응답 로직을 위해 RequestResponse객체에 접근하여 직접적인 응답을 컨트롤 해봅시다.

import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException
} from "@nestjs/common";
import { Request, Response } from "express";

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url
    });
  }
}

위 코드를 새 필터 파일을 만든 후 사용하자.
에러가 발생한다면 해당 status를 받고 timestamp를 찍고 해당 path까지 유동적으로 찍어준다.

profile
백엔드 개발자 정인교입니다!

0개의 댓글

관련 채용 정보