컨트롤러 내에 @ExceptionHandler가 달린 애노테이션으로 해당하는 예외들을 잡아서 원하는 값을 반환할 수 있다.
@RestController
public class MyRestController {
...
...
@ExceptionHandler(NullPointerException.class)
public Object nullex(Exception e) {
System.err.println(e.getClass());
return "myService";
}
}
위와 같이 NullPointerException에 대한 예외는 해당 메소드를 통해 원하는 값을 반환하게 할 수 있다.
ExceptionHandler는 특정 컨트롤러 클래스에서 사용한다.
반면에 ControllerAdvice는 ExceptionHandler를 여러 컨트롤러에 적용하기 위한 것이라고 생각하면 된다.
@RestControllerAdvice
public class MyAdvice {
@ExceptionHandler(CustomException.class)
public String custom() {
return "hello custom";
}
}
위와 같이 작성하면 RestController에 대해 CustomException이 터지면 해당 예외를 custom 메소드로 처리해서 반환할 수 있다.