06. @RestControllerAdvice

유승욱·2024년 5월 10일
0

Spring&React Project

목록 보기
6/9

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));
    }
}

0개의 댓글