small steps/1일 1코딩 - 코딩을 내 몸처럼
[1일1코딩][SpringBoot] @ExceptionHandler & @ControllerAdvice & @RestControllerAdvice 예외처리
꿈꾸는개발자maker
2022. 10. 21. 20:15
728x90
@ControllerAdvice
@Controller 어노테이션이 있는 모든 곳에서 예외처리 하는 기능
@ControllerAdvice 안에 있는 @ExceptionHandler는 모든 컨트롤러에서 발생하는 예외처리
@ControllerAdvice의 속성 설정을 통하여 원하는 컨트롤러나 패키지만 선택가능하며,
디폴트값은 모든 패키지에 있는 컨트롤러의 예외처리
@ExceptionHandler
특정 예외 클래스를 핸들링 가능하게 지원
@Controller , @RestController가 적용된 Bean 에서 발생하는 예외를 잡아서 하나의 메서드에서 처리해주는 기능
@ExceptionHandler에 설정한 예외가 발생하면 handler가 실행됨
@Controller, @RestController가 아닌 @Service나 @Repository가 적용된 Bean에서는 사용불가
@RestControllerAdvice
@ControllerAdvice + @ResponseBody → @RestControllerAdvice
@ControllerAdvice와 동일한 역할하나,
응답의 body에 객체를 넣어 반환이 가능
@RestControllerAdvice는 @RestController, @Controller에서 발생하는 예외 모두 잡을 수 있다
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
@ControllerAdvice
public class ExampleControllerAdvice {
final Logger logger = LoggerFactory.getLogger(getClass());
/**
* Exception 발생에 대한 예외처리
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception e) {
logger.error("handleException",e);
ModelAndView model = new ModelAndView("/error/error.html");
model.addObject("exception", e);
return model;
}
}
자료참조
https://tecoble.techcourse.co.kr/post/2021-05-10-controller_advice_exception_handler/
728x90
반응형