Spring Boot

[Spring Boot] 예외를 따로 처리하는 @ControllerAdvice

KEMON 2020. 6. 30. 02:19
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