[Spring] Exception 처리(Exception Handler, Controller Advice)

푸른별·2023년 9월 18일
0

Web

목록 보기
15/16
post-thumbnail

1. Error vs Exception

Error: 프로그램이 코드로 복구가 불가능한 경우의 오류
-> OutOfMemoryError와 같이 물리적인 한계에 봉착하는 등 직접적인 제어가 불가능한 경우의 문제를 의미합니다.

Exception: 프로그램의 문제를 미리 예상하여 어느 정도 처리가 가능한 오류
-> ArithmeticException을 예로 들면, 0으로 나누기가 발생할 때의 경우를 지정하여 문제 상황을 제어할 수 있는 경우 Exception으로 칭합니다.

이번 포스트는 이 중에서도 Exception을 처리하는 이야기를 하고자 합니다.

2. Exception Handler

  • @Controller 또는 @ControllerAdvice 클래스들은 @ExceptionHandler 메서드를 가지고 있고, 이를 통해 Controller 메서드들로부터 발생하는 예외들을 처리하게 됩니다.
@Controller
public class SimpleController {

	// ...

	@ExceptionHandler
	public ResponseEntity<String> handle(IOException ex) {
		// ...
	}
}
  • 추가로 특정 타입의 예외를 처리하고자 할 경우 다음과 같이 [@ExceptionHandler({FileSystemException.class, RemoteException.class})]
    를 작성하여 Exception을 원하는 만큼 처리할 수 있습니다.
//예외 유형을 여유롭게 설정(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) {
	// ...
}

3. Controller Advice

  • @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 {}

4. 참고

https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-exceptionhandler.html

https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-advice.html

profile
묵묵히 꾸준하게

0개의 댓글