Spring MVC 예외 처리 핸들러

Spring Web MVC

백기선님의 강의인 Spring Web MVC 강의를 듣고 공부한 내용을 정리한 글

@ExceptionHandler

예외를 처리하는 핸들러 @ExceptionHandler에 대해서 알아보자.

@ExceptionHandler는 특정 예외가 발생하는 요청을 처리하는 핸들러를 정의할 수 있는 애노테이션이다.

@ExceptionHandler(RuntimeException.class)
public String runtimeError(RuntimeException ex, Model model){
    model.addAttribute("message","runtime error");
    return "error" // view 템플릿 반환
}

REST API의 경우 응답 본문에 에러에 대한 정보를 담아주고, 상태 코드를 설정하려면 ResponseEntity를 주로 사용하기 때문에 REST API의 에러 핸들러를 만들 때는 ResponseEntity를 사용할 수도 있다!

Reference

인프런 백기선님의 스프링 Web MVC



© 2022. by minkuk

Powered by minkuk