1. Exception 정의

custom exception을 정의 src/common/exception/business.exception.ts

export class BusinessException extends HttpException {

  errorCode: ErrorCode;

  constructor(errorCode: ErrorCode) {
    super(errorCode.message, errorCode.code);
    this.errorCode = errorCode;
  }

  toResponse(requestUrl: string) {
    return {
      message: this.errorCode.message,
      code: this.errorCode.code,
      requestUrl: requestUrl,
      timestamp: new Date().toISOString()
    };
  }
}

src/common/exception/error.code.ts

export class ErrorCode {

  message: string;
  code: HttpStatus;

  constructor(message: string, code: HttpStatus) {
    this.message = message;
    this.code = code;
  }

  static readonly SERVER_ERROR = new ErrorCode('서버에 문제가 발생했습니다. 잠시후 다시 시도해주세요.', HttpStatus.INTERNAL_SERVER_ERROR);
}

2. 필터 정의

src/common/exception/business.exception.filters.ts

import { BusinessException } from '../exception/business.exception';
import { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(BusinessException)
export class BusinessExceptionFilter implements ExceptionFilter {
  catch(exception: BusinessException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    response
      .status(exception.errorCode.code)
      .json(exception.toResponse(request.url));
  }
}

3. 필터 적용

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe({ transform: true, forbidUnknownValues: false }));
  app.useGlobalFilters(new BusinessExceptionFilter()); // 요기!
  await app.listen(3000);
}
bootstrap();

4. 결과

Untitled

잘 되는것을 확인할 수 잇슴.


Custom Exception…

대부분의 경우에서, custom excpetion을 쓸 필요가 없단다… Nest에 내장된 HTTP Exception을 사용하면 된다