지난 번에 에러 코드를 추가하였는데, 해당 에러 코드를 포함하면서 내부에서 Custom 예외를 발생시킬 때 사용할 최상위 예외를 작성하였다.
@Getter
public class ApplicationException extends RuntimeException {
@Serial
private static final long serialVersionUID = -8808014635391651324L;
private final ErrorCode errorCode;
public ApplicationException(String message, ErrorCode errorCode) {
super(message);
this.errorCode = errorCode;
}
}
이와 같이 구성한 이유는 다음과 같다.
또한 예외 핸들링을 할 때, 특별히 다른 예외 처리를 해야 하는 경우는
하위 예외 클래스로 핸들링하면 되고, 일반적인 경우는 공통 처리를 해주면 된다!
// 일반적인 예외 핸들링
@ExceptionHandler(ApplicationException.class)
public ResponseEntity<ApiResponse<Void>> handleApplicationException(ApplicationException e) {
ErrorCode errorCode = e.getErrorCode();
String message = e.getMessage();
ApiResponse<Void> response = ApiResponse.ofFail(errorCode, message);
return ResponseEntity.status(e.getErrorCode().getHttpStatusCode()).body(response);
}
// 기존과 다른 예외 핸들링
// MemberNotFoundException 은 ApplicationException 의 하위 예외
@ExceptionHandler(MemberNotFoundException.class)
public ResponseEntity<ApiResponse<Void>> handleApplicationException(ApplicationException e) {
// 기존과 다른 처리...
}