• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

Exception Filter와 관련하여 질문있습니다.

22.04.28 15:30 작성 조회수 348

0

안녕하세요. 14:00 쯤에 미들웨어에서 발생한 에러는 Exception Filter에서는 catch되지 않는다고 말씀하셔서 확인 해보기 위해 main.ts에서 미들웨어를 만들어서 테스트 해봤는데요. 저는 미들웨어서 throw한 에러도 Exception Filter에서 잡히는 것 같아 질문드립니다. 

main.ts의 코드는 아래와 같습니다.

//main.ts

  app.use((req, res, next) => {
    throw new HttpException('미들웨어 에러 테스트', 400);
    next();
  });
 
//http-exception.filter.ts
import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';
import { 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 status = exception.getStatus();
    const error = exception.getResponse() as
      | string
      | { error: string; statusCode: number; message: string | string[] };
 
    console.log('Exception Filter 동작 확인용');
    console.log(error);

    return response.status(status).json({
      code: status,
      data: typeof error === 'string' ? error : error.message,
    });
  }
}
'/ '경로로 접속 시 콘솔은 다음과 같았습니다.
 
 
위 결과로 보아 미들웨어에서 발생한 에러도 Exception Filter에서도 에러를 잡아주는 것으로 판단 했는데요, 혹시 제가 잘못 테스트한 부분이 있으면 알려주시면 감사하겠습니다.
 

답변 2

·

답변을 작성해보세요.

0

yoon1139님의 프로필

yoon1139

질문자

2022.04.28

아래와 같이 작성했습니다.

// main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { HttpExceptionFilter } from './common/exception-filter/http-exception.filter';
import { HttpException, ValidationPipe } from '@nestjs/common';

declare const module: any;

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const PORT = process.env.PORT || 3000;

  const config = new DocumentBuilder()
    .setTitle('Sleact API')
    .setDescription('Sleact 개발을 위한 API 문서입니다.')
    .setVersion('1.0')
    .addCookieAuth('connect.sid')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);

  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
    }),
  );
  app.useGlobalFilters(new HttpExceptionFilter());

  app.use((req, res, next) => {
    throw new HttpException('미들웨어 에러 테스트', 400);
    next();
  });

  await app.listen(PORT);
  console.log(`${PORT}번 포트에서 서버 실행 중 ✅`);

  if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => app.close());
  }
}
bootstrap();
 
혹시 main.ts의 코드 순서도 라이프 사이클과 동일하게 맞춰줘야 하는건가요!?

아뇨 큰 라이프사이클에서는 변화가 없습니다. global middleware들도 exception filter에 걸리는 게 맞네요. https://slides.com/yariv-gilad/nest-js-request-lifecycle/fullscreen#/1 보고 강좌 작성했었는데 저 슬라이드가 틀린 것 같습니다.

yoon1139님의 프로필

yoon1139

질문자

2022.04.28

답변 감사합니다.

0

main.ts 코드 순서 어떻게 하셨나요?