@Getter
public class CustomException extends RuntimeException implements Serializable {
private ErrorCode errorCode;
public CustomException(ErrorCode errorCode) {
super(errorCode.getMessage());
this.errorCode = errorCode;
}
}
여러 커스텀 예외에서 상속받을 CustomException Class를 정의
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum ErrorCode {
NO_SUCH_USER(400, "U001", "존재하지 않는 사용자 입니다.");
private int status;
private final String code;
private final String message;
ErrorCode(final int status, final String code, final String message) {
this.status = status;
this.code = code;
this.message = message;
}
public int getStatus() {
return status;
}
public String getCode() {
return code;
}
public String getMessage() {
return message;
}
}
Enum 클래스를 활용해서 에러 코드 관리
public class NoSuchUserException extends CustomException{
public NoSuchUserException() {
super(ErrorCode.NO_SUCH_USER);
}
}
CustomException을 상속받은 예외를 만들어 미리 작성해둔 ErrorCode를 부모클래스를 통해 연결해준다.
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(CustomException.class)
protected ResponseEntity<?> handleCustomException(CustomException e) {
log.error(e.getErrorCode() + " : " + e.getMessage());
ErrorCode errorCode = e.getErrorCode();
final ErrorResponse response = ErrorResponse.of(errorCode);
return new ResponseEntity<>(response, HttpStatus.resolve(errorCode.getStatus()));
}
}
(Rest)ControllerAdvice는 여러 컨트롤러에 대해 전역적으로 ExceptionHandler를 적용해준다.
위에서 보이듯 ControllerAdvice 어노테이션에는 @Component 어노테이션이 있어서 ControllerAdvice가 선언된 클래스는 스프링 빈으로 등록된다. 그러므로 우리는 다음과 같이 전역적으로 에러를 핸들링하는 클래스를 만들어 어노테이션을 붙여줌으로써 에러 처리를 위임할 수 있다.
이 코드를 통해 log를 찍어주고, 오류 응답을 반환한다.
@Getter
@Setter
@NoArgsConstructor
public class ErrorResponse {
private String message;
private String code;
private int status;
public ErrorResponse(ErrorCode code) {
this.message = code.getMessage();
this.status = code.getStatus();
this.code = code.getCode();
}
public static ErrorResponse of(ErrorCode code) {
return new ErrorResponse(code);
}
}
ErrorResponse는 위처럼 구성되어있다.
출처
https://mangkyu.tistory.com/204
https://veneas.tistory.com/entry/Java-%EC%BB%A4%EC%8A%A4%ED%85%80-%EC%98%88%EC%99%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0Custom-Exception