Exception filter란


Exception filter는 API 요청시 정상적인 반응이 나오지 못하고 error를 처리해야할 때 쓰인다.

분기마다 에러처리는 너무 번거롭고 재사용성도 떨어지므로 Exception filter를 사용한다.

Error


cats.controller.ts

 @Get()
  getAllCat() {
    throw new HttpException('api is broken', 401); // === throw new Error("")
  }

HttpException 을 통해 express의 throw new Error("") 와 같은 효과를 낸다.

    throw new HttpException(
      { success: false, message: 'this api is broken' },
      401,
    ); // overriding이 가능

HttpExceptionHttpException() 괄호 안에 작성해줌으로서 에러 응답에 대한 커스텀이 가능하다.

Exception filter 작성하기


http-exception.filter.ts

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();
    const error = exception.getResponse(); // controller에서 설정한 에러메세지

    // express : res.status(400).json({...})
    response.status(status).json({
      success: false,
      error: error,
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
    });
  }
}

http-exception.filter.ts파일 안에 HttpExceptionFilter를 작성함으로서 exception filter 기능을 추가해줌으로서 분기마다 HttpException 으로 error 처리를 해줄 필요가 없어진다. exception.getResponse()를 통해 controller에서 작성한 메세지를 가져올 수 있다.