nestJS API 예외처리 구현하기

Gyus·2022년 5월 17일
0

Exception filters

Nest는 어플리케이션 전반에 처리되지 않은 예외 사항을 처리하는 것을 담당하는 예외처리 계층과 함께한다. 너의 코드에 의해 예외사항이 처리되지 않았을때, 이것은 자동적으로 적절하게 유저 친화적으로 보내지는 레이어에 의해 잡힌다.

Built-in HTTP exceptions

Nest가 기본적으로 제공하는 exception들이 있다.(HttpException을 기반으로 하는)

  • BadRequestException
  • UnauthorizedException
  • NotFoundException
  • ForbiddenException
  • NotAcceptableException
  • RequestTimeoutException

이외에도 여러 exception을 제공한다. https://docs.nestjs.com/exception-filters

exceiption-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();

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

이 필터를 거쳐서 예외사항을 response에 담아줄 것

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() as
            | string
            | { error: string; statusCode: number; message: string | string[] };

        if (typeof error === 'string') {
            response.status(status).json({
                success: false,
                timestamp: new Date().toISOString(),
                path: request.url,
                error,
            });
        } else {
            response.status(status).json({
                success: false,
                timestamp: new Date().toISOString(),
                ...error,
            });
        }
    }
}

위 코드는 error의 결과 값이 string인지 아닌지 판별하여 보여주는 코드이다 원래 error의 값이 object와 string 둘다 가져올 수 있기 때문에 지정해 준다.


import {Controller, Get, HttpException, Param, UseFilters} from '@nestjs/common';
import { AppService } from './app.service';
import {CatsService} from "./cats/cats.service";
import {HttpExceptionFilter} from "./http-exception.filter";

@Controller()
export class AppController {
  constructor(
      private readonly appService: AppService,
      private readonly catsService: CatsService,) {}

  @Get()
  @UseFilters(HttpExceptionFilter)
  getHello(): string {
    throw new HttpException('api broken', 401)
    return this.catsService.hiCatservice();
  }
}

여기서 useFilters를 사용해서 해당 controller에 전체적으로 예외 처리를 적용 시킬 수 있다.

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(8000);
}
bootstrap();

아예 전역으로 처리하는 방법으로는 useGlobalFilters가 있다.

profile
푸로구래머

0개의 댓글