본문 바로가기
Spring

[Spring] 예외 처리 - 사용자 정의

by Bhinney 2022. 10. 27.

✔️ 사용자가 만들어 사용해야하는 경우가 존재한다

해당 내용도 계속해서 수정할 예정이다.


✅ 사용자 정의 예외처리 방법

1️⃣ 사용자 정의 예외를 위한 이넘 클래스를 만들어준다.

import lombok.Getter;

public enum ExceptionCode {
    MEMBER_NOT_FOUND(404, "Member Not Found");

    @Getter
    private int status;

    @Getter
    private String message;

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

2️⃣ RuntimeException을 상속 받은 BusinessLogicException을 구현해준다.

import lombok.Getter;

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

    public BusinessLogicException(ExceptionCode exceptionCode) {
        super(exceptionCode.getMessage());
        this.exceptionCode = exceptionCode;
    }
}

3️⃣ ErrorResponse에 받을 status 넘버와 message를 private으로 주입을 받고, of 메서드를 구현해준다.

@Getter
public class ErrorResponse {

	// 예외 코드
	private int status;

	// 예외 메세지
	private String message;

	private ErrorResponse(int status, String message) {
		this.status = status;
		this.message = message;
	}

	// BusinessLogicException 객체에 대한 ErrorResponse 생성
	public static ErrorResponse of(ExceptionCode exceptionCode) {
		return new ErrorResponse(exceptionCode.getStatus(), exceptionCode.getMessage());
	}
}

4️⃣ 전역 에러를 받는 클래스에 BusinessLogicException을 처리할 메서드를 만들어준다.

@RestControllerAdvice
public class GlobalExceptionAdvice {
	...

	@ExceptionHandler
	public ErrorResponse handleBusinessLogicException(BusinessLogicException exception) {
		final ErrorResponse response = ErrorResponse.of(exception.getExceptionCode());

		return response;
	}
}

5️⃣ 결과

 

 


6️⃣ 사용자 정의 에러 코드 해당 코드로 받는 법

  • 위의 사진을 보면 메세지에는 404이지만 status는 200으로 들어온 것이 보인다.
  • 해당 문제는 코드를 조금만 바꿔주면 된다.
  • 아래처럼 해주면 status를 해당 코드로 받을 수 있다.
@RestControllerAdvice
public class GlobalExceptionAdvice {
	...

	@ExceptionHandler
	public ResponseEntity handleBusinessLogicException(BusinessLogicException exception) {
		final ErrorResponse response = ErrorResponse.of(exception.getExceptionCode());

		return new ResponseEntity<>(response, HttpStatus.valueOf(response.getStatus()));
	}
}


 

댓글