Spring Boot - Custom Exception
Custom Exception의 구조
Exception 클래스
ㆍ 위 사진은 Java에서 제공해주는 Exception 클래스에 대한 내용이다.
ㆍ Exception 클래스는 Throwable 클래스를 상속받는 형태이다.
ㆍ Exception 클래스의 생성자는 String 타입의 message를 받게 되는데, 해당 message가 클라이언트에게 전달될 메시지라는 것을 유추해볼 수 있다.
Throwable 클래스
ㆍ 위 사진은 Exception 클래스가 상속받고 있는 Throwable 클래스에 대한 내용이다.
ㆍ Exception 클래스의 생성자로부터 입력받은 message가 Throwable 클래스의 멤버 변수인 detailMessage로 된다는 것을 확인할 수 있다.
ㆍ 또한, getMessage() 메서드를 이용해서 예외에 대한 메시지를 가져올 수 있다는 것을 확인할 수 있다.
HttpStatus 클래스
ㆍ HttpStatus는 Enum 클래스이다. Enum 클래스란 서로 관련 있는 상수들을 모아 심볼릭 한 명칭의 집합으로 정의한 것을 의미한다. 즉, 클래스처럼 보이게 하는 상수이다.
ㆍ HttpStatus 클래스의 주요 항목은 value, series, reasonPhrase로 이루어져 있다.
ㆍ value는 예외의 상태 코드를 의미한다.
ㆍ series는 카테고리를 의미한다. 해당 예외가 어떤 타입에 포함이 되어있는 지를 정의하는 역할을 수행한다.
ㆍ reasonPhrase는 상태 코드가 내포하고 있는 의미를 정의한 값이다.
Custom Exception 적용
Constants 클래스 생성
public class Constants {
public enum ExceptionClass {
PRODUCT("Product"), ORDER("Order"), PROVIDER("Provider");
private String exceptionClass;
ExceptionClass(String exceptionClass) {
this.exceptionClass = exceptionClass;
}
public String getExceptionClass() {
return exceptionClass;
}
@Override
public String toString() {
return getExceptionClass() + " Exception. ";
}
}
}
ㆍ Constans 클래스는 ExceptionClass라는 Enum 클래스를 보유하고 있다.
CustomException 클래스 생성
public class CustomException extends Exception {
private static final long serialVersionUID = 4663380430591151694L;
private Constants.ExceptionClass exceptionClass;
private HttpStatus httpStatus;
public CustomException(Constants.ExceptionClass exceptionClass, HttpStatus httpStatus, String message) {
super(exceptionClass.toString() + message);
this.exceptionClass = exceptionClass;
this.httpStatus = httpStatus;
}
public Constants.ExceptionClass getExceptionClass() {
return exceptionClass;
}
public int getHttpStatusCode() {
return httpStatus.value();
}
public String getHttpStatusType() {
return httpStatus.getReasonPhrase();
}
public HttpStatus getHttpStatus() {
return httpStatus;
}
}
ㆍ CustomException 클래스는 Exception 클래스를 상속받은 형태이다.
ㆍ 직렬화를 위해서 serialVersionUID를 선언하였다.
ㆍ CustomException 클래스는 exceptionClass와 httpStatus를 필드로 가지고 있다.
GlobalExceptionHandler 클래스 수정
@ExceptionHandler(value = CustomException.class)
public ResponseEntity<Map<String, String>> ExceptionHandler(CustomException e) {
HttpHeaders responseHeaders = new HttpHeaders();
Map<String, String> map = new HashMap<>();
map.put("error type", e.getHttpStatusType());
map.put("code", Integer.toString(e.getHttpStatusCode()));
map.put("message", e.getMessage());
return new ResponseEntity<>(map, responseHeaders, e.getHttpStatus());
}
ㆍ GlobalExceptionHandler 클래스 내에 CustomException에 대한 예외를 처리해주는 메서드인 ExceptionHandler() 메서드를 위 코드와 같이 생성한다.
ㆍ CustomException에 대한 예외가 발생하면 해당 메서드를 통해 예외를 처리할 수 있다.
ProductController 클래스 수정
@PostMapping(value = "/product/exception")
public void exceptionTest() throws CustomException {
throw new CustomException(Constants.ExceptionClass.PRODUCT, HttpStatus.BAD_REQUEST, "의도한 에러가 발생하였습니다.");
}
ㆍ ProductController 클래스 내에 고의적으로 예외를 발생시키기 위한 exceptionTest() 메서드를 생성한다.
ㆍ 해당 메서드는 CustomException 클래스에 대한 예외를 발생시키는 역할을 수행한다.
테스트
예외 발생 및 확인
ㆍ 예외를 발생시키기 위해 서버로부터 요청을 한다.
ㆍ 위 사진과 같이 code, error type, message를 응답함으로써 클라이언트에게 어떤 에러가 발생했는지 공유하는 것을 확인할 수 있다.
GitHub - qlsdud0604/spring-boot-study
Contribute to qlsdud0604/spring-boot-study development by creating an account on GitHub.
github.com