Error: 프로그램이 코드로 복구가 불가능한 경우의 오류
-> OutOfMemoryError와 같이 물리적인 한계에 봉착하는 등 직접적인 제어가 불가능한 경우의 문제를 의미합니다.
Exception: 프로그램의 문제를 미리 예상하여 어느 정도 처리가 가능한 오류
-> ArithmeticException을 예로 들면, 0으로 나누기가 발생할 때의 경우를 지정하여 문제 상황을 제어할 수 있는 경우 Exception으로 칭합니다.
이번 포스트는 이 중에서도 Exception을 처리하는 이야기를 하고자 합니다.
@Controller
public class SimpleController {
// ...
@ExceptionHandler
public ResponseEntity<String> handle(IOException ex) {
// ...
}
}
//예외 유형을 여유롭게 설정(handle 메서드에 Exception 사용)
@ExceptionHandler({FileSystemException.class, RemoteException.class})
public ResponseEntity<String> handle(Exception ex) {
// ...
}
//예외 유형을 최대한 좁힌 경우(handle 메서드에 IOException으로 명시)
@ExceptionHandler({FileSystemException.class, RemoteException.class})
public ResponseEntity<String> handle(IOException ex) {
// ...
}
@Controller 대신 @ControllerAdvice 또는 @RestControllerAdvice 클래스에서 선언될 경우 모든 Controller에서 적용할 수 있습니다.
@ExceptionHandler, @InitBuilder, @ModelAttribute 메서드들은 @Controller 클래스 또는 해당 클래스 계층에서만 적용 가능합니다.
함께 사용할 때 주로 @ExceptionHandler로 예외 처리를 하지만, @InitBinder로 바인딩, 검증 설정을 추가하거나, @ModelAttribute로 모델 정보 설정을 할 수 있습니다.
다음과 같은 방식으로 ControllerAdvice의 요청 범위를 줄일 수 있습니다.
// Target all Controllers annotated with @RestController
@ControllerAdvice(annotations = RestController.class)
public class ExampleAdvice1 {}
// Target all Controllers within specific packages
@ControllerAdvice("org.example.controllers")
public class ExampleAdvice2 {}
// Target all Controllers assignable to specific classes
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
public class ExampleAdvice3 {}
https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-advice.html