@ExceptionHandler, @ControllerAdvice

태그
Spring
날짜
2024/01/28
2 more properties
예외처리를 위하여 @ExceptionHandler, @ControllerAdvice에 대하여 알아보자

@ControllerAdvice(@RestControllerAdvice)

@ControllerAdvice(@RestControllerAdvice)는 전역적으로 예외를 처리할 수 있게 해주는 어노테이션이다.
@Controller(@RestController) 가 붙은 컨트롤러에서 발생하는 예외를 처리할 수 있다.

@ExceptionHandler

@ExceptionHandler 어노테이션은 AOP를 이용한 예외처리 방식이다. 메소드에 선언하여 예외처리 하려는 클래스에 지정하면, 예외 발생 시 정의된 로직에 의해 처리된다.
→ 특정 예외가 발생하면 어떻게 처리할지 정해놓고, 처리할 수 있다.

@RestControllerAdvice, @ExceptionHandler를 활용한 예제

@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<?> handleException(Exception e) { return ResponseEntity .status(HttpStatus.INTERNAL_SERVER_ERROR) .body(response); } }
Java
복사
위처럼 작성하게 되면, 컨트롤러에서 발생하게 되는 Exception.class와 하위 클래스에 속한 예외가 발생 시 HttpStatus와 메세지지를 처리하게 된다.

Custom Exception 사용하는 방법

@ExceptionHandler(CustomException.class) public ResponseException handleCustomException(CustomException e, HttpServletRequest httpServletRequest) { log.error("URI : {}, CODE : {}", httpServletRequest.getRequestURI(), e.getErrorCode().name()); return ResponseException.builder() .statusCode(e.getErrorCode().getStatusCode()) .code(e.getErrorCode().name()) .message(e.getErrorCode().getMessage()) .build(); }
Java
복사

주의할 점

1.
프로젝트 하나에 하나의 @ControllerAdvice만 관리하는 것을 권장한다.
a.
여러 개를 사용하려면, basePackageClasses or basePackage같은 Selector를 사용해야 함
b.
이렇게 되면, OR연산을 통해 올바른 Selector를 찾아야 한다.
c.
해당 과정은 런타임 시점에 수행되어, 많아질수록 성능에 영향을 미치고 복잡성이 올라간다.
2.
직접 작성한 예외 클래스는 한 곳에서 관리되어야 한다.
3.
예외처리에 대한 우선순위는 @Order or @Priority를 기준으로 정렬되어 처리된다.