프로그래밍/JAVA Spring

[Spring 스프링] Spring MVC - ControllerAdvice(@ControllerAdvice와 @ExceptionHandler를 이용한 예외처리)

hectick 2023. 4. 20. 17:19

 

ControllerAdvice

예외처리를 하기 위한 @ExceptionHandler 어노테이션은 일반적으로 @Controller 또는 @RestController 어노테이션이 달린 클래스에 있는 메서드에 달 수 있다. 하지만 @ControllerAdvice, @RestControllerAdvice(@ControllerAdvice + @ResponseBody) 클래스 안에도 달 수 있다. 여기다가 달면 모든 컨트롤러에 적용된다. 이 점을 이용해서 예외처리 부분을 별도의 컨트롤러로 빼낼 수 있다.

    @RestControllerAdvice
    public class ExceptionController {

        @ExceptionHandler({IllegalArgumentException.class, NullPointerException.class})
        public ResponseEntity<PlayFailResponse> handle(Exception exception) {
            PlayFailResponse playFailResponse = new PlayFailResponse(exception.getMessage());
            return ResponseEntity.badRequest().body(playFailResponse);
        }
    }

 

 

별도의 설정을 해주면 모든 컨트롤러가 아닌 일부 컨트롤러에만 적용할 수도 있다.

이 때는 local한 @ExceptionHandler -> global한 @ExceptionHandler 순서로 우선순위가 정해진다.

    // @RestController가 달린 모든 컨트롤러들을 대상으로 한다.
    @ControllerAdvice(annotations = RestController.class)
    public class ExampleAdvice1 {}

    // 특정 패키지에 있는 컨트롤러들을 대상으로 한다.
    @ControllerAdvice("org.example.controllers")
    public class ExampleAdvice2 {}

    // 특정 컨트롤러를 대상으로 한다.
    @ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
    public class ExampleAdvice3 {}