@ExceptionHandler는 Spring MVC에서 예외 처리를 위해 사용되는 어노테이션이다. @ExceptionHandler을 사용하면 컨트롤러 메서드에서 발생한 예외를 효과적으로 처리할 수 있습니다.
아래 코드에서 class ExceptionHandlerController에서 발생하는 NullPointerException은 이제 String nullPointerExceptionHandler()
가 잡아서 return "error/nullPointer";
로 보내준다.
@Controller
public class ExceptionHandlerController {
@GetMapping("controller-null")
public String nullPointerExceptionTest() {
String str = null;
System.out.println(str.charAt(0)); // str이 null이므로 예외 발생
return "/";
}
// NullPointerException이 발생하면 동작
@ExceptionHandler(NullPointerException.class)
public String nullPointerExceptionHandler(NullPointerException exception) {
System.out.println("controller 레벨의 exception 처리");
return "error/nullPointer";
}
}
try catch말고 @ExceptionHandler를 사용하는 이유
MVC 컨트롤러에서 try-catch 블록 대신 @ExceptionHandler를 사용하는 것은 예외 처리 로직의 집중화, 일관성, 프레임워크 지원, 명시적 처리, 유연성 등의 장점 때문입니다. 이를 통해 컨트롤러 코드의 가독성과 유지보수성을 향상시킬 수 있다.
(try catch를 아예 사용을 안 하는 것은 아니다.)특정 상황에서는 try-catch를 직접 사용해야 할 수도 있지만, MVC 컨트롤러에서는 @ExceptionHandler가 일반적으로 더 선호되는 방식이라고 한다.
@ControllerAdvice를 사용하면 애플리케이션 전체에서 발생하는 예외를 효율적으로 처리할 수 있습니다.@ControllerAdvice를 통해 예외 처리 로직을 중앙 집중화하고, 프로젝트에 일관된 예외 처리 방식을 구현할 수 있다.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NullPointerException.class)
public String nullPointerExceptionHandler(NullPointerException exception) {
System.out.println("Global 레벨의 exception 처리");
return "error/nullPointer";
}
/* 상위 타입인 Exception을 이용하면 구체적으로 작성하지 않은 타입의 에러가 발생하더라도
* 처리가 가능하므로 default 처리 용도로 사용할 수 있다. */
@ExceptionHandler(Exception.class)
public String defaultExceptionHandler(Exception exception) {
return "error/default";
}
}
"Spring Boot Interceptor is an additional component that will intercept every request and response dispatch and perform some operations on it." geeksforgeeks
=> spring Boot Interceptor는 요청과 응답의 흐름을 중간에 가로채서 추가적인 작업을 수행할 수 있는 구성 요소로 이를 통해 애플리케이션의 기능을 확장하거나 공통 로직을 적용할 수 있다.(boot의 interceptor와 spring의 interceptor는 같은 개념이라서 가져옴)