Spring Boot 애플리케이션 실행 시
아래와 같은 오류가 발생하며 서버가 기동되지 않았다.
Ambiguous @ExceptionHandler method mapped for [class java.lang.Exception]
에러 로그에 따르면
GlobalExceptionHandler 내부의 @ExceptionHandler 설정이 충돌하고 있었다.
GlobalExceptionHandler에는 다음과 같은 예외 처리 메서드가 존재했다.
@ExceptionHandler(MethodArgumentNotValidException.class)
public ApiResponse<?> handleValidationException(...)
@ExceptionHandler(Exception.class)
public ApiResponse<?> handleException(Exception e)
문제는 예외 상속 구조에 있었다.
MethodArgumentNotValidException
└─ BindException
└─ Exception
즉,
MethodArgumentNotValidException은Exception의 하위 클래스이로 인해 Spring은
“이 예외를 어느 핸들러가 처리해야 할지 모르겠다”
라고 판단했고,
ApplicationContext 초기화 단계에서 실패하게 되었다.
@ExceptionHandler(Exception.class)는 너무 광범위가장 일반적인 예외 처리 대상이었던
Exception.class를 다음과 같이 변경했다.
@ExceptionHandler(RuntimeException.class)
public ApiResponse<?> handleRuntimeException(RuntimeException e) {
return ApiResponse.error(
ErrorCode.INTERNAL_ERROR.name(),
ErrorCode.INTERNAL_ERROR.getDefaultMessage()
);
}
RuntimeException인가?RuntimeException 기반Exception)은 직접 다루는 경우가 거의 없음/health 엔드포인트 정상 응답{
"success": true,
"data": "OK",
"error": null
}
@ExceptionHandler는