Spring

Spring global 예외처리

sehunbang 2024. 2. 19. 17:00

사실 예외처리 로직 자체는 매우 공통적

필요한 곳에서 Error를 만들어서 던지고, 그 Error를 받는곳이 어디든

그 Error 내용을 담아서 클라이언트에 보내주면 됩니다.

 

 

@ControllerAdvice 사용

  • Spring에서 예외처리를 위한 클래스 레벨 애너테이션
  • 모든 Controller에서 발생한 예외를 처리하기 위해 사용됩니다.
  • @ExceptionHandler메서드를 정의하여 예외를 처리하는 로직을 담을 수 있습니다.

 

 

@ControllerAdvice   사용하는 이유? :

 

1. 예외처리를 중앙 집중화하기 좋습니다.

2. Controller 예외처리 로직을 반복하지 않아도 됨 

3. 예외 처리 로직을 모듈화 ( 관리하기 쉽다 ---> 개발 생산성을 향상시키는 것도 가능합니다.)

 

 

 

 

@RestControllerAdvice =  @ControllerAdvice + @ResponseBody

 

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