Local Exception Controller
Controller 내에서 발생하는 Exception만 처리한다.
@Controller
public class LocalExceptionController {
@GetMapping("/business1")
public String business_method() throws BusinessException1 {
boolean b = true;
if(b) {
throw new BusinessException("업무예외1");//예외발생시 BusinessException1으로 던짐 @ExceptionHandler(BusinessException.class)
}
return "forward:/WEB-INF/views/business_result.jsp";//정상실행의 경우
}
/*****************예외처리******************/
@ExceptionHandler(BusinessException.class)
public String handle_business_exception(BusinessException e,Model model) {
model.addAttribute("error_msg", e.getMessage());
return "forward:/WEB-INF/views/business_error_result.jsp";
}
}
@Controller에 business_method() 메소드가 GetMapping 되어있다.
Exception이 발생한 상황을 만들어
Custom Exception인 BusinessException()이 을 던져주었다.
BusinessException이 발생하면
동일 Controller 내부에 있는
@ExceptionHandler()를 탐색한다.
BusinessException.class를 받는 Exception Handler를 찾아 Exception을 처리한다.
handle_business_exception은 Exception과 Model을 파라메타로 받는다.
Model은 error_msg를 넘겨주기 위해서 받았다.
Exception이 가지고 있는 msg를 e.getMessage()로 받아 model의 속성에 등록하고
error_result.jsp로 forwarding 한다.
그러면 error_result.jsp에서 model의 "error_msg"를 꺼내 쓸 수 있다.
공통 예외 처리
/*
* 모든콘트롤러의 공통예외를 처리하기위한 ControllerAdvice
*/
@ControllerAdvice
public class GlobalCommonExceptionControllerAdvice {
@ExceptionHandler(Exception.class)
public String handle_exception(Exception e) {
return "foward:/WEB-INF/views/global_error_result.jsp";
}
@ExceptionHandler(RuntimeException.class)
public String handle_runtime_exception(RuntimeException e) {
return "foward:/WEB-INF/views/global_error_result.jsp";
}
}
모든 컨트롤러의 공통예외를 처리하기 위해서 ExceptionHandler를 가진 Controller를 만든다.
이때, @Controller가 아닌 @ControllerAdvice 어노테이션을 사용한다.
@PostMapping("/user_login_action")
public String user_login_action(@ModelAttribute(name="fuser") User user, Model model, HttpSession session) throws Exception {
try {
userService.login(user.getUserId(), user.getPassword());
session.setAttribute("sUserId", user.getUserId());
return "user_main";
} catch (PasswordMismatchException e) {
model.addAttribute("msg2",e.getMessage());
return "user_login_form";
} catch (UserNotFoundException e) {
model.addAttribute("msg1",e.getMessage());
return "user_login_form";
}
}
if문이나 ExceptionHandler로 Exception을 처리하는 방식 말고도
try-catch문으로 Exception을 잡는 방식이다.
'Java > Spring Boot' 카테고리의 다른 글
Spring JSP 국제화 (0) | 2023.09.13 |
---|---|
Spring Boot Controller Mapping + View Resolver (0) | 2023.09.12 |
Spring Boot (0) | 2023.09.12 |
Spring Boot에서 JSP 사용하기 (0) | 2023.09.12 |
Spring Boot Application Overview (1) (0) | 2023.09.11 |