• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    해결됨

HttpExceptionFilter에 단순 HttpException 예외처리도 필요하지 않나요?

23.08.29 23:12 작성 조회수 218

0

HttpExceptionFilter에서 에러처리시

exception.getStatus() 로 err 변수값을 넣을떄

HttpException 의 경우 string 타입

BadRequestException, UnauthorizedException 와 같이 미리 정의된 경우 { message: any; statusCode: number } 타입

class-validator의 경우 { error: string; statusCode: 400; message: string[] } 타입의 3가지 형태가 되는데

이번강의에서 string 타입 자체를 제거하셧는데 HttpException 를 사용하게되면 에러 메시지가 제대로 안 날라 가게 됩니다.

class-validator를 도입하면서 HttpException 케이스를 제거 하신거 같은데 해당 예외도 포함은 되어있어야 하지 않나요?
class-validator 가 완전히 HttpException 를 대체하게 한다면 HttpException를 사용못하게 막을 방법이 있을까요?

import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  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 err = exception.getResponse() as
      | string
      | { message: any; statusCode: number }
      | { error: string; statusCode: 400; message: string[] };

    //class-validator
    if (typeof err !== 'string' && err.statusCode === 400) {
      return response.status(status).json({
        success: false,
        code: err.statusCode,
        data: err.message,
      });
    }

    //HttpException
    if (typeof err == 'string') {
      return response.status(status).json({
        success: false,
        code: status,
        data: err,
      });
    }

    //BadRequestException, UnauthorizedException
    return response.status(status).json({
      success: false,
      code: status,
      data: err.message,
    });
  }
}

답변 1

답변을 작성해보세요.

0

네, err 자체가 객체가 아니라 string인 케이스도 처리 필요하겠네요.