Exception filter

2022. 11. 28. 17:44·라이브러리 & 프레임워크/NestJS

예외 필터(Exception filter)

Nest 에서 제공하는 전역 예외 필터 이외에 직접 예외 필터 레이어를 두어 원하는 대로 예외를 핸들링할 수 있습니다.

예외 필터(Exception filter)는 예외가 일어났을 때 에러 로그를 남기거나 응답 객체를 원하는 대로 변경하고자 하는 등의 요구사항을 해결하고자 할 때 사용합니다.

예외가 발생했을 때 모든 예외(Error)를 잡아서 원하는 대로 핸들링할 수 있는 예외 필터를 만들어보고자 합니다. 

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

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: Error, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();
    const err = exception.getResponse() as
      | { message: any; statusCode: number }
      | { error: string; statusCode: 400; message: string[] };
      
    // HttpException이 아닌 예외(알 수 없는 에러)거나 InternalServerErrorException인 예외인 경우  
    if (!(exception instanceof HttpException) || (exception instanceof InternalServerErrorException)) {
      return response.status(500).json({
        success: false,
        code: 500,
        data: '서버 내부에서 발생한 에러'
      });
    }
    
    response.status(status).json({
      success: false,
      code: status,
      data: err.message,
    });
  }
}

@Catch( ) 데코레이터는 처리되지 않은 모든 예외를 잡으려고 할 때 사용합니다.

어플리케이션에서 다루는 대부분의 예외는 HttpException을 상속받는 클래스들(NotFoundException, UnauthorizedException, ConflictException 등)로 처리합니다.

HttpException이 아닌 예외는 알 수 없는 에러로 InternalServerErrorException 으로 처리되도록 합니다.

예외 필터(Exception filter) 적용

특정 엔드포인트에 적용

@Controller('users')
export class UsersController {
  // ...
  @UseFilters(HttpExceptionFilter)
  @Post()
  join(@Body() joinRequestDto: JoinRequestDto) {
    return this.userService.join(joinRequestDto);
  }
  // ...
}

특정 컨트롤러 전체에 적용

@Controller('users')
@UseFilters(HttpExceptionFilter)
export class UsersController {
  // ...
}

애플리케이션 전체에 적용

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalFilters(new HttpExceptionFilter()); // 전역 필터 적용
  await app.listen(8080);
}

출처

https://docs.nestjs.com/exception-filters

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reac

docs.nestjs.com

https://wikidocs.net/158651 

'라이브러리 & 프레임워크 > NestJS' 카테고리의 다른 글

[Nest] WebSocket 서버 구성하기(feat. Socket.io)  (0) 2022.12.12
[NestJS] Authentication  (0) 2022.11.29
Validation  (0) 2022.11.28
Mapped Types  (0) 2022.11.28
[TypeORM] 마이그레이션  (0) 2022.11.27
'라이브러리 & 프레임워크/NestJS' 카테고리의 다른 글
  • [Nest] WebSocket 서버 구성하기(feat. Socket.io)
  • [NestJS] Authentication
  • Validation
  • Mapped Types
rondeveloper
rondeveloper
  • rondeveloper
    Ron's learning record
    rondeveloper
  • 전체
    오늘
    어제
    • 분류 전체보기 (103) N
      • k8s (3) N
      • AWS (1)
      • 리눅스 (5)
      • Docker (8)
      • 라이브러리 & 프레임워크 (14)
        • React (2)
        • NestJS (8)
        • Spring (0)
        • Django (3)
        • FastAPI (1)
      • 웹 (2)
        • Nginx (1)
      • 프로그래밍 언어 (29)
        • HTML (0)
        • CSS (0)
        • JavaScript (21)
        • Python (3)
        • Node.js (0)
        • TypeScript (4)
        • Java (1)
      • Today I learned (9)
      • 알고리즘 (9)
        • 백준 (0)
        • 프로그래머스 (8)
        • 개념 (1)
      • 티끌모아 태산 (5)
        • 하루에 영단어 하나씩 (5)
        • 독서 (0)
      • 시행착오 (3)
      • 데이터베이스 (2)
        • MySQL (0)
      • 컴퓨터 과학 (8)
        • 네트워크 (2)
        • 운영체제 (0)
        • 데이터베이스 (2)
        • 자료구조 (4)
      • 포트폴리오 (4)
        • JJINCAFE IN SEOUL (4)
        • CODEUNICORN (0)
      • 회고 (0)
      • CICD (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    자바스크립트
    Docker
    iterable
    mysql
    typescript
    조인
    FastAPI
    IP 주소
    컨테이너
    Kubectl
    코딩테스트
    Python
    프로그래머스
    생활코딩
    기초
    Til
    네트워크
    django
    도커
    nestjs
    리눅스
    모듈
    typeorm
    Kubernetes
    스택
    배열
    레벨2
    javascript
    반복문
    redis
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
rondeveloper
Exception filter
상단으로

티스토리툴바