728x90
예외를 처리할 때 아래와 같이 try catch방식이 아니라
public class RestaurantNotFoundException extends RuntimeException {
//예외처리 함수
public RestaurantNotFoundException(Long id){
super("Could not find restaurant" + id);
}
}
@GetMapping("/restaurants/{id}")
public Restaurant detail(@PathVariable("id") Long id){
try{
Restaurant restaurant = restaurantService.getRestaurant(id); //기본정보 + 메뉴정보
}catch(RestaurantNotFoundException e){
}
return restaurant;
}
따로 @ControllerAdvice를 이용해서 class를 만들면 코드의 분리가 간편해진다!
@ControllerAdvice(예외처리Class) : 실제로 예외를 던져주고 예외를 받아서 처리
@ResponseStatus(HttpStatus.NOT_FOUND) : 404를 리턴해 주기 위함
@ControllerAdvice
public class RestaurantErrorAdvice {
@ResponseStatus(HttpStatus.NOT_FOUND) //exception시 404 return
@ExceptionHandler(RestaurantNotFoundException.class)
public void handleNotFound(){
}
}
728x90
'Spring Boot' 카테고리의 다른 글
[Spring Boot] Entity의 주요 어노테이션 (0) | 2020.07.04 |
---|---|
[Spring Boot] HTTP 통신 방식 과 REST의 개념 (0) | 2020.07.04 |
[SpringBoot] Lombok ToString 특정 필드 출력 안하는 법 (0) | 2020.06.17 |
[Spring Boot] Gradle build daemon disappeared unexpectedly (it may have been killed or may have crashed) 오류 해결방법 (0) | 2020.06.16 |
[Spring Boot] Spring initializr로 스프링 부트 시작하기 (0) | 2020.06.15 |