@ControllerAdvice는 스프링 MVC에서 전역적으로 예외를 처리하고, 전체 애플리케이션에서 일관된 응답을 제공하기 위해 사용되는 어노테이션입니다.
기본적인 사용 방법은 다음과 같습니다:
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.ResponseEntity;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleAllExceptions(Exception ex) {
return new ResponseEntity<>("An unexpected error occurred", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@ControllerAdvice("com.example.controllers")
public class SpecificPackageExceptionHandler {
// 예외 처리 메서드들...
}
@ControllerAdvice(annotations = RestController.class)
public class RestControllerExceptionHandler {
// 예외 처리 메서드들...
}
@ControllerAdvice
public class GlobalModelAttributes {
@ModelAttribute("globalAttribute")
public String addGlobalAttribute() {
return "This is a global attribute";
}
}
@ControllerAdvice
public class GlobalBindingInitializer {
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.addValidators(new MyCustomValidator());
}
}
@RestControllerAdvice는 @ControllerAdvice와 @ResponseBody를 결합한 어노테이션입니다. REST API에서 사용하기 적합합니다:
@RestControllerAdvice
public class GlobalRestExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<ErrorResponse> handleUserNotFound(UserNotFoundException ex) {
ErrorResponse error = new ErrorResponse("USER_NOT_FOUND", ex.getMessage());
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
}
@ExceptionHandler@ControllerAdvice 클래스 내부의 @ExceptionHandler@ControllerAdvice가 적용된 예외 처리를 테스트할 때:
@SpringBootTest
@AutoConfigureMockMvc
class GlobalExceptionHandlerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testHandleUserNotFound() throws Exception {
mockMvc.perform(get("/users/999"))
.andExpect(status().isNotFound())
.andExpect(content().string("User not found with id: 999"));
}
}
@ControllerAdvice에 넣으면 코드가 복잡해질 수 있습니다.@ControllerAdvice 클래스의 책임을 명확히 분리하세요.@ControllerAdvice는 스프링 MVC 애플리케이션에서 전역적인 예외 처리와 공통 설정을 구현하는 데 매우 유용한 도구입니다. 이를 통해 애플리케이션 전체에 일관된 예외 처리 로직을 적용할 수 있으며, 코드의 중복을 줄이고 유지보수성을 향상시킬 수 있습니다. 다만, 과도한 사용은 오히려 복잡성을 증가시킬 수 있으므로, 적절한 균형을 유지하는 것이 중요합니다. 전역 예외 처리, 공통 모델 속성 추가, 바인딩/검증 규칙 설정 등 다양한 용도로 활용할 수 있어, 스프링 MVC 애플리케이션의 구조를 개선하는 데 큰 도움이 됩니다.
@ExceptionHandler
@RestController
@ResponseBody
@InitBinder
@ModelAttribute