23. 에러 컨트롤러 및 커스텀 익셉션 만들기v4

송민경's avatar
Mar 15, 2024
23. 에러 컨트롤러 및 커스텀 익셉션 만들기v4

1. myExceptionHandler 만들기

  • 모든 예외가 RuntimeException으로 처리
어떤 예외가 발생하더라도 항상 첫 번째 400 호출
항상 error/400 페이지로 이동
notion image
package shop.mtcoding.blog._core.utils; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice // RUNTIME 예외가 터지면 여기로 오류가 모여 처리함 public class myExceptionHandler { // 커스텀 예외를 만들어서 런타임 예외 상속하기 @ExceptionHandler(RuntimeException.class) public String ex400(RuntimeException e){ return "errors/400"; } @ExceptionHandler(RuntimeException.class) public String ex401(RuntimeException e){ return "errors/401"; } @ExceptionHandler(RuntimeException.class) public String ex403(RuntimeException e){ return "errors/403"; } @ExceptionHandler(RuntimeException.class) public String ex404(RuntimeException e){ return "errors/404"; } @ExceptionHandler(RuntimeException.class) public String ex500(RuntimeException e){ return "errors/500"; } }
 

2. 커스텀 예외를 만들어서 런타임 예외 상속하기

package shop.mtcoding.blog._core.utils.exception; public class Exception400 extends RuntimeException{ public Exception400(String msg) { super(msg); } }
package shop.mtcoding.blog._core.utils.exception; public class Exception401 extends RuntimeException{ public Exception401(String msg) { super(msg); } }
package shop.mtcoding.blog._core.utils.exception; public class Exception404 extends RuntimeException{ public Exception404(String msg) { super(msg); } }
package shop.mtcoding.blog._core.utils.exception; public class Exception403 extends RuntimeException{ public Exception403(String msg) { super(msg); } }
package shop.mtcoding.blog._core.utils.exception; public class Exception500 extends RuntimeException{ public Exception500(String msg) { super(msg); } }
 

3. myExceptionHandler 수정하기

package shop.mtcoding.blog._core.utils; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import shop.mtcoding.blog._core.utils.exception.*; @ControllerAdvice // RUNTIME 예외가 터지면 여기로 오류가 모여 처리함 public class myExceptionHandler { // 커스텀 예외를 만들어서 런타임 예외 상속하기 @ExceptionHandler(Exception400.class) public String ex400(RuntimeException e){ return "errors/400"; } @ExceptionHandler(Exception401.class) public String ex401(RuntimeException e){ return "errors/401"; } @ExceptionHandler(Exception403.class) public String ex403(RuntimeException e){ return "errors/403"; } @ExceptionHandler(Exception404.class) public String ex404(RuntimeException e){ return "errors/404"; } @ExceptionHandler(Exception500.class) public String ex500(RuntimeException e){ return "errors/500"; } @ExceptionHandler(Exception.class) public String exUnKnown(RuntimeException e){ // DB에 에러 로그 남기기 // 관리자에게 알리기 // 이메일 보내기 return "errors/unKnown"; } }
 

4. msg 담기

package shop.mtcoding.blog._core.utils; import jakarta.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import shop.mtcoding.blog._core.utils.exception.*; @ControllerAdvice // RUNTIME 예외가 터지면 여기로 오류가 모여 처리함 public class myExceptionHandler { // 커스텀 예외를 만들어서 런타임 예외 상속하기 @ExceptionHandler(Exception400.class) public String ex400(RuntimeException e, HttpServletRequest request){ request.setAttribute("msg", e.getMessage()); return "errors/400"; } @ExceptionHandler(Exception401.class) public String ex401(RuntimeException e, HttpServletRequest request){ request.setAttribute("msg", e.getMessage()); return "errors/401"; } @ExceptionHandler(Exception403.class) public String ex403(RuntimeException e, HttpServletRequest request){ request.setAttribute("msg", e.getMessage()); return "errors/403"; } @ExceptionHandler(Exception404.class) public String ex404(RuntimeException e, HttpServletRequest request){ request.setAttribute("msg", e.getMessage()); return "errors/404"; } @ExceptionHandler(Exception500.class) public String ex500(RuntimeException e, HttpServletRequest request){ request.setAttribute("msg", e.getMessage()); return "errors/500"; } @ExceptionHandler(Exception.class) public String exUnKnown(RuntimeException e){ // DB에 에러 로그 남기기 // 관리자에게 알리기 // 이메일 보내기 return "errors/unKnown"; } }
 

5. UserController 에서updateForm 수정해서 확인하기

package shop.mtcoding.blog.user; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import shop.mtcoding.blog._core.utils.exception.Exception400; import shop.mtcoding.blog._core.utils.exception.Exception401; @RequiredArgsConstructor @Controller public class UserController { private final UserRepository userRepository; private final HttpSession session; @PostMapping("/user/update") public String update(UserRequest.UpdateDTO reqDTO){ User sessionUser = (User) session.getAttribute("sessionUser"); User newSessionUser = userRepository.updateById(sessionUser.getId(), reqDTO.getPassword(), reqDTO.getEmail()); session.setAttribute("sessionUser", newSessionUser); System.out.println(sessionUser); return "redirect:/"; } @PostMapping("/join") public String join(UserRequest.JoinDTO reqDTO) { User sessionUser = userRepository.save(reqDTO.toEntity()); session.setAttribute("sessionUser", sessionUser); return "redirect:/"; } @PostMapping("/login") public String login(UserRequest.LoginDTO reqDTO) { User sessionUser = userRepository.findByUsernameAndPassword(reqDTO); session.setAttribute("sessionUser", sessionUser); return "redirect:/"; } @GetMapping("/join-form") public String joinForm() { return "user/join-form"; } @GetMapping("/login-form") public String loginForm() { return "user/login-form"; } @GetMapping("/user/update-form") // session(mypage)에 있으니 id가 필요 없음 public String updateForm(HttpServletRequest request) { User sessionUser = (User) session.getAttribute("sessionUser"); if(sessionUser == null) { throw new Exception401("인증되지 않았어요. 로그인해주세요"); } User user = userRepository.findById(sessionUser.getId()); // 없어도 상관은 없음 request.setAttribute("user", user); return "user/update-form"; } @GetMapping("/logout") public String logout() { session.invalidate(); return "redirect:/"; } }
notion image
Share article

vosw1