예외처리
@RestControllerAdvice
- RestController에서 발생하는 특정 상황에 대해 처리하는 클래스로 지정
@ExceptionHandler
- 지정한 예외에 대해 직접 컨트롤할 수 있도록 하는 어노테이션
- @ExceptionHandler(value={예외 클래스, ...})
-->예외클래스의 배열을 입력 받는다
1번 예시
- 빈공백이 있을경우
- Status:403 반환
- 결과: 절못된 입력을 받았습니다 출력
package com.hmy.springbasic.exceptionHandler;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class CustomExceptionHandler {
@ExceptionHandler(value={MethodArgumentNotValidException.class})
public ResponseEntity<String> customException(
MethodArgumentNotValidException exception
){
exception.printStackTrace();
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("잘못된 입력입니다.");
}
}
- 실행화면

2번 예시
- Body안에 아무것도 등록이 되어있지 않을때 예외처리
- Status:404 반환
- 결과: 요청 데이터를 읽을수 없습니다 출력
@ExceptionHandler(value={HttpMessageNotReadableException.class})
public ResponseEntity<String> notReadableException(
HttpMessageNotReadableException exception
){
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body("요청 데이터를 읽을수 없습니다.");
}
}
- 실행화면
