@ControllerAdvice
- 예시 코드
- @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(CustomException.class) public ResponseEntity<String> handleCustomException(CustomException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).
- 정상 코드와 예외 처리 코드 분리 가능
- @ExceptionHandler만 사용 시, 정상 코드와 예외 처리 코드가 하나의 컨트롤러 위치
- @Component로 메타 어노테이션이 지정되어 있으므로
component Scanning을 통해 Spring 빈으로 등록 가능 - 대상으로 지정한 여러 컨트롤러에 @ExceptionHandler , @InitBinder 기능을 부여
- 글로벌 적용 : 대상을 지정하지 않으면 모든 컨트롤러에 적용
- RequestMappingHandlerMapping과 ExceptionHandlerExceptionResolver
- Controller advice 빈을 찾아 런타임에 적용
- 적용 순서
- 글로벌 @ModelAttribute 및 @InitBinder 메서드 - @Controller의 로컬 메서드 - @ControllerAdvice의 글로벌 @ExceptionHandler
- @RestControllerAdvice
- @RestControllerAdvice = @ControllerAdvice + @ResponseBody
- return value : response body 메시지 변환 (HTML view 아님)
- 대상 콘트롤러 지정 방법
- 특정 패키지 직접 지정
- 예시 코드
- @ControllerAdvice(com.example.controllers") public class GlobalControllerAdvice { @ExceptionHandler(CustomException.class) public ResponseEntity<String> handleCustomException(CustomException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage()); } }
- 특정 어노테이션이 있는 컨트롤러 지정
- 예시 코드
- @ControllerAdvice(annotations = MyCustomAnnotation.class) public class GlobalControllerAdvice { @ExceptionHandler(CustomException.class) public ResponseEntity<String> handleCustomException(CustomException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage()); } }
- 특정 클래스 지정
- 예시 코드
- @ControllerAdvice(assignableTypes = MyCustomControllerInterface.class) public class GlobalControllerAdvice { @ExceptionHandler(CustomException.class) public ResponseEntity<String> handleCustomException(CustomException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage()); } }
- 대상 컨트롤러 지정 생략 시 글로벌 적용
- 특정 패키지 직접 지정
'Develop > Spring' 카테고리의 다른 글
[Spring Web MVC] Exceptions - @ExceptionHandler (0) | 2023.04.17 |
---|---|
[Spring Web MVC] Handler Methods - Return Values (0) | 2023.04.17 |
[Spring Web MVC] Handler Methods - MethodArgument (0) | 2023.04.17 |
[Spring Web MVC] Request Mapping - consumes, produces (0) | 2023.04.17 |
[Spring Web MVC] Request Mapping - Parameters, headers (0) | 2023.04.17 |