컨트롤러마다 ExceptionHandler 를 넣어주는것은 비효율적이다.
글로벌하게 처리해보자.

@ControllerAdvice는 Spring에서 예외처리를 위한 클래스 레벨 애너테이션입니다.@ControllerAdvice 가 붙은 클래스에서는 @ExceptionHandler메서드를 정의하여 예외를 처리하는 로직을 담을 수 있습니다.@ControllerAdvice 를 사용하는 이유?@ControllerAdvice를 사용하면 예외 처리 로직을 모듈화하여 관리하기 쉽기 때문에, 팀 내에서 공통된 예외 처리 로직을 공유하거나 다른 팀에서 예외 처리를 참고할 수 있습니다. 이를 통해 개발 생산성을 향상시키는 것도 가능합니다.@ControllerAdvice + @ResponseBody
GlobalExceptionHandler.java 를 따로 만들어준다.
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler({IllegalArgumentException.class})
public ResponseEntity<RestApiException> handleException(IllegalArgumentException ex) {
RestApiException restApiException = new RestApiException(ex.getMessage(), HttpStatus.BAD_REQUEST.value());
return new ResponseEntity<>(
// HTTP body
restApiException,
// HTTP status code
HttpStatus.BAD_REQUEST
);
}
}