복's

[ Nest JS ] 예외 클래스 만들기 및 필터에서 예외 받기 본문

교육/SW 정글 프로젝트(나만무)

[ Nest JS ] 예외 클래스 만들기 및 필터에서 예외 받기

나복이 2023. 11. 16. 01:24
728x90

이전에 필터를 만들고 예외 클래스를 구현하고 받을 생각을 하고 있었다가 이제 예외 객체를 만들게 되었다.

물론 예외 처리가 실무에서 이렇게 되는지는 모르지만 나는 내가 원하는데로 진행했다.

 

1) Exception 클래스

...
export class DoWithException extends Error {
    name: string;
    errorCode: number;
    statusCode: number;

    constructor(message, errorCode, statusCode){
        super(message);
        this.name = 'DoWithException';
        this.errorCode = errorCode;
        this.statusCode = statusCode;
    }

    getStatus(){
        return this.statusCode;
    }
}

// 밑의 코드들은 샘플 코드

enum DoWithErrorCode {
    TestError = '0010'
}

enum DoWithErrorMsg {
    TestError = 'This is not permmited'
}

@Injectable()
export class DoWithExceptions {
    NotPermitted = new DoWithException(DoWithErrorMsg.TestError, DoWithErrorCode.TestError, HttpStatus.BAD_REQUEST);
}

먼저 HttpException이 아니라 모든 exception에 대해서 제어하기 위해서 Error 최상위 객체를 상속 받았다.

getStatus는 나도 상태 코드를 생성자에서 받기 때문에 HttpException과 같이 사용할 때 에러가 나지 않도록 구현했다.

 

enum 타입을 2개 선언해서 메세지랑 코드를 관리하기로 했다. (근데 따로 관리해도 되나 싶기도 하고)

 

마지막으로 @Injectable()을 선언하고 클래스 내부에 에러를 미리 생성하고, 의존성을 주입 받은 이 후 사용하려고 계획중이다.

 

2) 모듈 생성

Controller에서 사용 테스트를 하기 위해서 모듈을 생성하고, providers에 등록한다.

...
@Module({
    controllers: [MoviesController],
    providers: [MoviesService, Logger, DoWithExceptions]
})
export class MoviesModule {}

 

 

3) 의존성 주입 이 후 사용

의존성 주입하고 HttpException과 DoWithExceptions를 번갈아 가며 테스트 해봤다.

throw new InternalServerErrorException();
throw this.doWithExceptions.NotPermitted;

강제로 두 개의 코드를 번갈아가며 throw 시켜서 결과를 확인했을 때

[ HttpException ]
[ DoWithException(Custom Exception) ]

필터에서 logging을 통해서 확인한 결과인데 이제 response만 에러에 따라서 처리해주면 될 것 같다. 

 

4) 필터

처음에는 문자열 비교가 아니라 getResponse를 통해서 확인하려고 했는데, 커스텀 에러가 아닌 DB나 토큰 같은 에러도 생각해서 문자열 비교하는걸로 변경했다. (이것도 틀릴 수 있음)

...
if(exception.name === 'DoWithException'){
    this.logger.debug("DoWithException");
} else {
    this.logger.debug("HTTPException");
}
this.logger.error("여기 에러 났습니다 동네 사람들!!!", exception);
...

 

 

이제 exception에 대해서 어느정도 제어를 갖고 컨트롤 할 수 있는 코드가 된 것 같다.

728x90