API 서버는 화면이 없는 상태에서 개발되기 때문에 잘못된 파라미터 등으로 인한 서버 내부의 예외 처리를 @RestControllerAdvice로 처리해 주는 것이 안전하다.
CustomControllerAdvice
@RestControllerAdvice
public class CustomControllerAdvice {
@ExceptionHandler(NoSuchElementException.class)
protected ResponseEntity<?> notExist(NoSuchElementException e) {
String msg = e.getMessage();
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("msg", msg));
}
@ExceptionHandler(MethodArgumentNotValidException.class)
protected ResponseEntity<?> notExist(MethodArgumentNotValidException e) {
String msg = e.getMessage();
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(Map.of("msg", msg));
}
}