▶ 스프링 예외처리 방법(3가지)(중복적용 가능함)
1. 메서드별 예외처리(try-catch / throws) -> 1순위로 적용됨
2. 하나의 컨트롤러에서 발생하는 예외를 모아서 처리하는 방법 -> 2순위
-> 메서드에 작성 @ExceptionHandler
3. 애플리케이션 전역에서 발생하는 예외를 모아서 처리하는 방법 -> 3순위
-> 클래스로 작성 @ControllerAdvice
// 예외처리 2. 예시 (현재 Controller에서만 예외처리 해줌)
// MemberController.java
public class MemberController {
@ExceptionHandler
public String exceptionHandler(Exception e, Model model) {
e.printStackTrace();
model.addAttribute("errorMsg", "서비스 이용중 문제가 발생했습니다.");
return "common/errorPage";
}
}
// 예외처리 3. 예시
// spring.common.exception.java
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler(Exception.class) //최상위 에러로 모든 클래스의 에러 잡아주기
public String exceptionHandler(Exception e, Model model) {
e.printStackTrace();
model.addAttribute("errorMsg", "서비스 이용중 문제 발생!! 관리자에게 문의해 주세요.");
return "common/errorPage";
}
}