💡 학습 목표
1. 커스텀 예외의 필요성 이해 :
기본 예외 처리 방식의 한계를 인식하고, 커스텀 예외를 통해 보다 세밀한 에러 관리를 이해한다.
2. 커스텀 예외 클래스 생성 :
다양한 상황에 맞는 사용자 정의 예외 클래스를 생성하는 방법을 학습한다.
3. 글로벌 예외 처리기(Global Exception Handler) 구현 :
@ControllerAdvice와 @ExceptionHandler를 활용하여 전역적으로 예외를 처리하는 방법을 익힌다.
1. 커스텀 예외 클래스 생성
Exception400
401 ... 500 생략
package com.tenco.blog_v2.common.errors;
public class Exception400 extends RuntimeException {
// throw new Exception400("야 너 잘못 던졌어"); <-- 사용하는 시점에 호출 모습
public Exception400(String msg) {
super(msg);
}
}
- @ControllerAdvice: 전역적인 예외 처리를 담당하는 클래스임을 나타낸다.
- @ExceptionHandler: 특정 예외가 발생했을 때 실행할 메서드를 지정한다.
- ModelAndView: 뷰와 데이터를 함께 반환하는 객체로, 에러 페이지와 메시지를 전달한다.
GlobalExceptionHandler
package com.tenco.blog_v1.common;
import com.tenco.blog_v1.common.errors.*;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 400 Bad Request 예외 처리
* @param ex
* @param model
* @return
*/
@ExceptionHandler(Exception400.class)
public ModelAndView handleException400(Exception400 ex, Model model) {
ModelAndView mav = new ModelAndView("err/400");
mav.addObject("msg", ex.getMessage());
return mav;
}
/**
* 401 Unauthorized 예외 처리
* @param ex
* @param model
* @return
*/
@ExceptionHandler(Exception401.class)
public ModelAndView handleException401(Exception401 ex, Model model) {
ModelAndView mav = new ModelAndView("err/401");
mav.addObject("msg", ex.getMessage());
return mav;
}
/**
* 403 Forbidden 예외 처리
* @param ex
* @param model
* @return
*/
@ExceptionHandler(Exception403.class)
public ModelAndView handleException403(Exception403 ex, Model model) {
ModelAndView mav = new ModelAndView("err/403");
mav.addObject("msg", ex.getMessage());
return mav;
}
/**
* 404 Not Found 예외 처리
* @param ex
* @param model
* @return
*/
@ExceptionHandler(Exception404.class)
public ModelAndView handleException404(Exception404 ex, Model model) {
System.out.println("err message : " + ex.getMessage());
ModelAndView mav = new ModelAndView("err/404");
mav.addObject("msg", ex.getMessage());
return mav;
}
/**
* 500 Internal Server err 예외 처리
* @param ex
* @param model
* @return
*/
@ExceptionHandler(Exception500.class)
public ModelAndView handleException500(Exception500 ex, Model model) {
ModelAndView mav = new ModelAndView("err/500");
mav.addObject("msg", ex.getMessage());
return mav;
}
}
'Spring Boot > Blog 프로젝트 만들기(JPA)' 카테고리의 다른 글
인터셉터 만들어 보기 (0) | 2024.10.11 |
---|---|
회원 정보 수정 (0) | 2024.10.11 |
에러 페이지 만들기 (1) | 2024.10.11 |
회원 가입 (0) | 2024.10.10 |
게시글 수정 (0) | 2024.10.10 |