Custom Exception 처리는 좀 더 체계적으로 예외를 관리하고 처리하는 방법
이 방식을 사용하면 에러 발생 시 코드가 어디에서 문제가 생겼는지, 왜 발생했는지를 명확하게 알 수 있음
public interface CustomException {
HttpStatus status();
String message();
String serverMessage();
}
이 stomException 인터페이스는 예외 발생 시 필요한 정보들을 반환하는 역할을 함
HttpStatus status(): 예외가 발생했을 때 반환할 HTTP 상태 코드를 결정String message(): 사용자에게 보여줄 예외 메시지String serverMessage(): 개발자나 서버 로그용으로 저장할 메시지@Getter
@RequiredArgsConstructor
public class CustomRuntimeException extends RuntimeException {
private static final String STATUS = "STATUS";
private static final String MESSAGE = "MESSAGE";
private final CustomException customException;
public ResponseEntity<Map<String, String>> sendError() {
Map<String, String> messages = new LinkedHashMap<>();
messages.put(STATUS, customException.status().toString());
messages.put(MESSAGE, customException.message());
return ResponseEntity.status(customException.status()).body(messages);
}
}
이 클래스는 실제로 예외를 발생시키는 역할을 함
CustomException 인터페이스를 구현한 예외 객체를 받아와서 이를 기반으로 에러를 처리해줌.CustomException 객체가 정함