개요

Custom Exception 처리는 좀 더 체계적으로 예외를 관리하고 처리하는 방법

이 방식을 사용하면 에러 발생 시 코드가 어디에서 문제가 생겼는지, 왜 발생했는지를 명확하게 알 수 있음


1. CustomException 인터페이스

public interface CustomException {
    HttpStatus status();
    String message();
    String serverMessage();
}

stomException 인터페이스는 예외 발생 시 필요한 정보들을 반환하는 역할을 함

동작 원리:


2. CustomRuntimeException 클래스

@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);
    }
}

이 클래스는 실제로 예외를 발생시키는 역할을 함

동작 원리:

  1. CustomException 객체를 받아서 처리: 예외가 발생하면, 해당 예외가 어떤 상태 코드와 메시지를 가질지 CustomException 객체가 정함