지난 게시글에서는 Spring MVC 애플리케이션에서 @RestControllerAdvice를 이용하여 예외를 처리하는 방법, 예외에 대한 메시지를 클라이언트에 전달하는 방법에 대해 작성했다.
👉🏻 @RestControllerAdvice를 이용한 예외처리 공통화
이번에는 서비스 계층에서 발생하는 비즈니스 로직의 상황에 맞게,
개발자가 각각 커스텀하여 API 계층에서 예외를 처리하는 방법에 대해 알아보자.
public class BusinessLogicException extends RuntimeException {
@Getter
private ExceptionCode exceptionCode;
public BusinessLogicException(ExceptionCode exceptionCode) {
super(exceptionCode.getMessage());
this.exceptionCode = exceptionCode;
}
}
RuntimeException
을 상속받음super
를 활용하여 예외 메시지를 전달함ExceptionCode
라는 예외 정보 객체를 멤버 변수로 지정하여, 구체적인 예외 정보를 제공함ExceptionCode
정보만 바꿔서 처리할 수 있음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;
}
}
// 멤버를 조회하는데 이미 존재하는 경우 예외를 던짐
@Service
public class MemberService {
...
private void verifyExistsEmail(String email) {
Optional<Member> member = memberRepository.findByEmail(email);
if (member.isPresent()) {
throw new BusinessLogicException(ExceptionCode.MEMBER_EXISTS);
}
}
}
@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()));
}
// 여러 케이스의 예외 처리 추가하여 사용
...
}