@ExceptionHandler를 사용해서 예외를 깔끔하게 처리할 수 있게 되었지만, 정상 코드와 예외 처리 코드가 하나의 컨트롤러에 섞여 있다.
@ControllerAdvice 또는 @RestControllerAdvice를 사용하면 둘을 분리할 수 있다.
@Slf4j
@RestControllerAdvice
public class ExControllerAdvice {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(IllegalArgumentException.class)
public ErrorResult illegalExHandler(IllegalArgumentException e) {
log.error("[exceptionHandler] ex", e);
return new ErrorResult("BAD", e.getMessage());
}
@ExceptionHandler
public ResponseEntity<ErrorResult> userExHandler(UserException e) {
log.error("[exceptionHandler] ex", e);
ErrorResult errorResult = new ErrorResult("USER-EX", e.getMessage());
return new ResponseEntity<>(errorResult, HttpStatus.BAD_REQUEST);
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler
public ErrorResult exHandler(Exception e) {
log.error("[exceptionHandler] ex", e);
return new ErrorResult("EX", "내부 오류");
}
}
@ControllerAdvice는 대상으로 지정한 여러 컨트롤러에 @ExceptionHandler, @InitBinder 기능을 부여해주는 역할을 한다.
@ControllerAdvice에 대상을 지정하지 않으면 모든 컨트롤러에 적용된다. (글로벌 적용)
@RestControllerAdvice는 @ControllerAdvice와 같고 @ResponseBody가 추가되어 있다. (@Controller와 @RestController의 차이와 같다)
// @RestController라고 지정된 컨트롤러에서만 적용
@ControllerAdvice(annotations = RestController.class)
public class ExampleAdvice1 {}
// 해당 패키지 포함 하위 폴더에 있는 모든 컨트롤러에 적용 ex) 상품,주문 컨트롤러 분리
@ControllerAdvice("org.example.controllers")
public class ExampleAdvice2 {}
// 직접 컨트롤러 지정
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
public class ExampleAdvice3 {}
특정 애노테이션이 있는 컨트롤러를 지정할 수 있다.
특정 패키지를 직접 지정할 수도 있다. 패키지 지정의 경우 해당 패키지와 그 하위에 있는 컨트롤러가 대상이 된다.
대상 컨트롤러 지정을 생략하면 모든 컨트롤러에 적용된다.