Spring/예외처리

[Spring] 예외처리 - 비지니스 로직

한비Skyla 2024. 6. 15. 11:21

개발자가 의도적으로 예외를 던질 수 있는 상황 

- 백엔드 서버와 외부 시스템과의 연동에서 발생하는 에러 

- 시스템 내부에서 조회하려는 리소스가 없는 경우

 

💡GlobalExceptionAdvice 

 @ExceptionHandler
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ErrorResponse handleBusinessLogicException(BusinessLogicException e) {
    
    // ErrorResponse 에서 BusinessLogicException를 파라미터로 받았을 때. 
    (1) final ErrorResponse response = ErrorResponse.of(e);
    
    
    // ErrorResponse 에서 BusinessLogicException의 ExceptionCode를 파라미터로 받았을 때. 
    (2) final ErrorResponse response = ErrorResponse.of(e.getExceptionCode());
        return response;
    }

 

 

 

💡ErrorResponse 

    public static ErrorResponse of(BusinessLogicException businessLogicException) {
        return new ErrorResponse(businessLogicException.getExceptionCode().getStatus(),
                businessLogicException.getExceptionCode().getMessage(), null, null );
    }

    // 여기서 우리가 필요한 코드는 ExceptionCode 인 것임. 확장성이 높은 것은 클래스이므로,
    // 그 안의 클래스 변수를 넣어주는 것이 더 좋음.
    public static ErrorResponse of(ExceptionCode exceptionCode) {
        return new ErrorResponse(exceptionCode.getStatus(),
                exceptionCode.getMessage(), null, null );
    }

 

 

클래스 자체를 받는 것 보다는

이 안의 클래스 변수인 ExceptionCode 를 받음으로써,

클래스의 확장성을 높일 수 있음!!