✅ ControllerAdvice란?
스프링 애플리케이션에서 모든 컨트롤러에서 발생한 예외를 처리하는 데 사용된다.
@ControllerAdvice
는 REST와 비 REST 형식 모두 예외처리를 한다. 기본적으로 응답을 JSON이나 REST API에 적합한 형식으로 변환하지 않기 때문에, RESTful 서비스의 경우 응답을 직렬화하려면, 메소드에 @ResponseBody
를 추가해야 한다.import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseBody
public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseEntity<String> handleGenericException(Exception ex) {
return new ResponseEntity<>("An unexpected error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
→ 위 코드에서 JSON 형식으로 반환하기 위해
@ResponseBody
를 추가한 것을 확인할 수 있다.✅ RestControllerAdvice란?
@RestController
어노테이션이 붙은 컨트롤러에서 발생하는 예외를 AOP를 적용하여 전역적으로 처리할 수 있는 어노테이션이다. 위의
@ControllerAdvice
와 @ResponseBody
의 기능을 결합한 것으로, 응답이 JSON 형식으로 반환된다.import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
// ResourceNotFoundException 예외에 대한 예외처리
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
// Exception 예외에 대한 예외처리
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGenericException(Exception ex) {
return new ResponseEntity<>("An unexpected error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
위 코드처럼
@ExceptionHandler
를 통해 여러가지 특정 예외를 처리하도록 설정할 수 있다. 하나의 ExceptionHandler에서 여러 예외를 처리하려면 클래스 배열을 사용할 수도 있다.@RestControllerAdvice(basePackages = "com.example.controllers")
public class SpecificExceptionHandler {
// 예외 처리
}
@RestControllerAdvice(assignableTypes = {ControllerA.class, ControllerB.class})
public class SpecificExceptionHandler {
// 예외 처리
}
또,
@RestControllerAdvice
는 특정 패키지만을 탐지하도록 범위를 지정하거나 특정 컨트롤러 클래스를 탐지하도록 범위를 설정할 수도 있다.Share article