레스토랑 예약 사이트 만들기 4 - 예외 처리

없는 페이지 요청에 대한 예외처리

@Test
public void 없는_페이지에대한_예외처리를_한다() throws Exception{
given(restaurantService.getRestaurant(404L)).willThrow(new RestaurantNotFoundException(404L));
ResultActions resultActions = mockMvc.perform(get("/restaurants/404"));

resultActions
.andExpect(status().isNotFound())
.andExpect(content().string("{}"));
}
public class RestaurantNotFoundException extends RuntimeException{
public RestaurantNotFoundException(Long id) {
super("Could not find Restaurant" + id );
}
}
@ControllerAdvice
public class RestaurantErrorAdvice {

@ResponseBody
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(RestaurantNotFoundException.class)
public String handleNotFound(){
return "{}";
}
}

Service 계층에서의 예외처리

@Test
public void 없는_레스토랑을_가져온다() {
assertThatThrownBy(() -> {
Restaurant restaurant = restaurantService.getRestaurant(404L);
}).isInstanceOf(RestaurantNotFoundException.class);
// Restaurant restaurant = restaurantService.getRestaurant(404L);
}
public Restaurant getRestaurant(Long id) {
Optional<Restaurant> optional = restaurantRepository.findById(id);

if (optional.isPresent()) {
List<MenuItem> menuItems = menuItemRepository.findAllByRestaurantId(id);
Restaurant restaurant = new Restaurant();
restaurant.setMenuItems(menuItems);
return restaurant;
}else{
throw new RestaurantNotFoundException(id);
}
}
Share