비즈니스 로직에 어울리게 예외 처리를 커스텀하는 방법

Lundy·2023년 11월 18일
0

Spring Boot

목록 보기
6/6
post-thumbnail

지난 게시글에서는 Spring MVC 애플리케이션에서 @RestControllerAdvice를 이용하여 예외를 처리하는 방법, 예외에 대한 메시지를 클라이언트에 전달하는 방법에 대해 작성했다.

👉🏻 @RestControllerAdvice를 이용한 예외처리 공통화

이번에는 서비스 계층에서 발생하는 비즈니스 로직의 상황에 맞게,

개발자가 각각 커스텀하여 API 계층에서 예외를 처리하는 방법에 대해 알아보자.

1. 비즈니스 로직 예외 처리할 클래스 정의

public class BusinessLogicException extends RuntimeException {
    @Getter
    private ExceptionCode exceptionCode;

    public BusinessLogicException(ExceptionCode exceptionCode) {
        super(exceptionCode.getMessage());
        this.exceptionCode = exceptionCode;
    }
}
  • RuntimeException 을 상속받음
    • 상위 클래스이므로 생성자 super 를 활용하여 예외 메시지를 전달함
  • ExceptionCode 라는 예외 정보 객체를 멤버 변수로 지정하여, 구체적인 예외 정보를 제공함
    • 예외를 처리할 다양한 case에서 ExceptionCode 정보만 바꿔서 처리할 수 있음

2. 예외 코드 (enum) 정의

public enum ExceptionCode {
    MEMBER_NOT_FOUND(404, "Member not found"),
    MEMBER_EXISTS(409, "Member exists"),
    NOT_IMPLEMENTATION(501, "Not Implementation");
		// 다양한 유형의 예외를 추가하여 사용
		...

    @Getter
    private int status;

    @Getter
    private String message;

    ExceptionCode(int code, String message) {
        this.status = code;
        this.message = message;
    }
}

3. 서비스 계층에서 예외 throw

// 멤버를 조회하는데 이미 존재하는 경우 예외를 던짐 

@Service
public class MemberService {
    ...

    private void verifyExistsEmail(String email) {
        Optional<Member> member = memberRepository.findByEmail(email);

        if (member.isPresent()) {
            throw new BusinessLogicException(ExceptionCode.MEMBER_EXISTS);
        }
    }
}

4. Advice에서 예외 catch

@RestControllerAdvice
public class GlobalExceptionAdvice {
		...    

		@ExceptionHandler
    public ResponseEntity handleBusinessLogicException(BusinessLogicException e) {

        final ErrorResponse response = ErrorResponse.of(e.getExceptionCode());

        return new ResponseEntity<>(response,
                HttpStatus.valueOf(e.getExceptionCode().getStatus()));
    }
		
		// 여러 케이스의 예외 처리 추가하여 사용
		...
}
profile
아주 사소하더라도

0개의 댓글

관련 채용 정보