04. HttpException

유현준·2022년 8월 15일
0

hello! Nest

목록 보기
4/17

HttpException

  • nest에서 예외처리를 위해 제공되는 클래스이다.
  • HttpException을 이용해 Filter를 생성하면, 예외처리에 대한 코드 재사용성을 늘릴 수 있다.(중복되거나 반복되는 예외처리 작성을 크게 줄일 수 있다.)

1) httpException-filter 예시

// 에외처리 필터
// 필터 적용은 controller 단/전역 단에서 적용 가능
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();
    //httpexception 객체로 전달되는 에러메시지(string/object(404에러일 경우)로 있음.)
    const error = exception.getResponse() as string | { error: string; statusCode: number; message: string | string[] };
    // type이 Object인 404 에러의 분기 처리(404에러를 포함한 에러 예외 처리)

    // 1. 404 외의 에러
    if (typeof error === 'string') {
      response.status(status).json({
        success: false,
        statusCode: status,
        timestamp: new Date().toISOString(),
        path: request.url,
        error: error,
      });
    } else {
      // 2. 404 에러
      response.status(status).json({
        success: false,
        timestamp: new Date().toISOString(),
        ...error, //비구조할당으로 객체를 풀어서 그 안의 값만 정렬
      });
    }
  }
}
  • response.status() ~~ 이하 내용을 오버라이딩 하여, 예외처리를 커스텀할 수 있다.

2) httpException-filter 적용 예시

// httpException-filter 적용한 컨트롤러
 @Get()
  @UseFilters(HttpExceptionFilter) // 필터 적용
  getCats(): string {
    throw new HttpException('api is broken', 401);
    return this.catsService.getCats();
  }

// 전역에서 httpException-filter 적용(main.ts)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './http-exception.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalFilters(new HttpExceptionFilter());
  await app.listen(3000);
}
bootstrap();

참고강의

profile
차가운에스프레소의 개발블로그입니다. (22.03. ~ 22.12.)

0개의 댓글