Spring

[Spring] Exception (예외) - ControllerAdvice

동그리담 2024. 6. 28. 00:09

ControllerAdvice와 RestControllerAdvice

@ExceptionHandler 를 사용해서 예외를 깔끔하게 처리할 수 있게 되었지만, 정상 코드와 예외 처리 코드가 하나의 
컨트롤러에 섞여 있다. @ControllerAdvice 또는 @RestControllerAdvice 를 사용하면 둘을 분리할 수 있다.

  • @ControllerAdvice는 대상으로 지정한 여러 컨트롤러에 @ExceptionHandler, @InitBinder 기능을 부여해주는 역할을 한다.
    • 대상을 지정하지 않으면 모든 컨트롤러에 적용 (글로벌 적용) 
    • 참고
      • @ExceptionHandler : 예외처리 메서드 지정 애너테이션
      • @InitBinder : Controller로 들어오는 요청에 대해 추가적인 설정을 하고 싶을 때 사용
  • @RestControllerAdvice : @ControllerAdvice에 @RestController가 붙은 

 

대상 지정 방법

//애너테이션 지정 @RestController
@ControllerAdvice(anntations = RestController.class)
public class ExampleAdvice1 {}

//패키지 지정 (하위 모두 포함)
@ControllerAdvice("org.example.controllers") 
public class ExampleAdvice2 {}


//클래스 지정(부모클래스지정, 특정 컨트롤러 지정)
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
public class ExampleAdvic3 {}

 

Exception 정리

기존 서블렛은 WAS에 sendError를 보내서 다시 에러 페이지를 렌더링 하는 과정을 거쳤지만

스프링에서 ExceptionResolver를 호출하면서 에러를 정상흐름으로 바꾸는 기회가 한번 더 생긴다고 이해하면 좋을 것 같다.

 

출처: https://tan-sog.tistory.com/90