project 가 커질수록 REST Controller 의 개수도 늘어날 수 있다. 그러나 이전에 작성한 exception handler 는 StudentRestController 라는 특정 Controller 에서만 유효하다. 따라서 모든 Controller 에서 사용할 수 있는 centralized 되고 global 한 exception handler 가 필요하다.

Spring @ControllerAdvice

@ControllerAdvice annotation 은 통합 예외 처리 센터라고 할 수 있다. 대표적으로 아래 두 개의 특성을 가진다.

  • request 를 pre-process 하여 controller 에게 전달
  • exception handling 을 위하여 response 를 post-process
Global Exception Handling

위와 같이 Controller Advice 를 통하도록 설계하면 될 것 같다. Development Process 는 다음과 같다.

  1. Create new @ControllerAdvice
  2. Refactoring REST service: remove exception handlind code
  3. Add exception handling code to @ControllerAdvice
Step 1: Create new @ControllerAdvice
@ControllerAdvice
public class StudentExceptionHandler {
	...
}

먼저 StudentExceptionHandler class 를 새로 생성하고 @ControllerAdvice annotation 으로 지정하자.

Step 2: Refactoring REST service - remove exception handlind code

기존에 특정 Controller 안에 있던 exception handling code 부분을 모두 삭제한다.

Step 3: Add exception handling code to @ControllerAdvice

Step 2 에서 삭제한 code snippet 을 그대로 StudentExceptionHandler 에 paste 하여 사용한다.

이렇게 되면 exception handler 가 특정 Controller 에 종속되는 것이 아니라 Controller Advice 가 모든 exception handling 을 처리하게 된다.

@ControllerAdvice 는 AOP(Aspect-Oriented Programming) 의 원리를 기반으로 동작하며, Controller 에서 발생하는 exception 을 global 하게 처리하기 위한 기능이다. AOP 의 SoC(Seperation of Concerns) 개념을 활용하여 모든 Controller 에 공통된 logic 을 적용하여 처리할 수 있다.

test 해보면, 기존 Controller 에 exception handling 부분이 없어졌으나 새로 만들어진 Controller Advice 가 exception handling 을 성공적으로 수행한 것을 볼 수 있다.