코딩/Nest.js

GlobalFilters

춘 몽 2024. 4. 22. 21:55

- 파일 만들기 => commons/filter => http-exception.filter.ts

import {
  Catch,
  ExceptionFilter,
  HttpException,
  InternalServerErrorException,
} from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException) {
    const status = exception.getStatus();
    const message = exception.message;

    console.log('예외 발생', message, status);
    throw new InternalServerErrorException('서버 오류');
  }
}

- main.ts 파일 수정

  app.useGlobalFilters(new HttpExceptionFilter());

 

근데 GlobalFilters를 설정안해도 기본적으로 500코드를 반환한다고 하니 위에 위에 코드를 굳이 작성할 필요는 없을듯.

아마 따로 예외코드들과 그에 따른 응답을 지정해줘야할때 필요할듯.

 

 

https://docs.nestjs.com/exception-filters#binding-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 Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

 

'코딩 > Nest.js' 카테고리의 다른 글

Swagger  (0) 2024.04.24
Global Pipes  (0) 2024.04.22
환경변수 ConfigModule  (0) 2024.04.22
오류 상태 코드  (0) 2024.04.20
Multer  (0) 2024.04.18