
핸들러의 필요성
[ 에러 컨트롤러 만들기 ]

ExceptionHandler라는 이름으로 만들면 안된다. 이미 클래스가 있기 때문!!!

throw나 Exception이 발생하면 다 여기로 오게 만들거다!!
에러만 터뜨리는 클래스! 핸들러!
주의할 것 !!! ★
[ 커스텀 exception 만들자! ]

Exception400
package shop.mtcoding.blog._core.errs.exception;
public class Exception400 extends RuntimeException {
public Exception400(String msg) {
super(msg);
}
}
Exception401
package shop.mtcoding.blog._core.errs.exception;
public class Exception401 extends RuntimeException {
public Exception401(String msg) {
super(msg);
}
}
Exception403
package shop.mtcoding.blog._core.errs.exception;
public class Exception403 extends RuntimeException {
public Exception403(String msg) {
super(msg);
}
}
Exception404
package shop.mtcoding.blog._core.errs.exception;
public class Exception404 extends RuntimeException {
public Exception404(String msg) {
super(msg);
}
}
Exception500
package shop.mtcoding.blog._core.errs.exception;
public class Exception500 extends RuntimeException {
public Exception500(String msg) {
super(msg);
}
}
이제 throw exception400, throw exception403 이런 식으로, 내가 터뜨리고 싶은 에러 페이지를 골라서 터트릴 수가 있게 됨!!
[ MyExceptionHandler - 컨트롤러 ]
package shop.mtcoding.blog._core.errs;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import shop.mtcoding.blog._core.errs.exception.*;
//RuntimeException이 터지면 해당 파일로 오류가 모인다!!
@ControllerAdvice
public class MyExceptionHandler {
//애는 Exception
@ExceptionHandler(Exception400.class)
public String ex400(Exception e, HttpServletRequest request) {
request.setAttribute("msg", e.getMessage());
return "err/400";
}
//애는 Exception
@ExceptionHandler(Exception401.class)
public String ex401(Exception e, HttpServletRequest request) {
request.setAttribute("msg", e.getMessage());
return "err/401";
}
//애네들은 RuntimeException
@ExceptionHandler(Exception403.class)
public String ex403(RuntimeException e, HttpServletRequest request) {
request.setAttribute("msg", e.getMessage());
return "err/403";
}
@ExceptionHandler(Exception404.class)
public String ex404(RuntimeException e, HttpServletRequest request) {
request.setAttribute("msg", e.getMessage());
return "err/404";
}
@ExceptionHandler(Exception500.class)
public String ex500(RuntimeException e, HttpServletRequest request) {
request.setAttribute("msg", e.getMessage());
return "err/500";
}
}
애네들은 내가 잡을 수 있는 에러들인데... 내가 못 잡는 모든 exception... 에러는 어떻게 하는걸까? -> unknown이란 걸 하나 더 만들어줌!
[ unknown ]

NullPointException 이런건 커스텀 되어있지 않으니까 exUnknown으로 간다.
StackOverFlow 이런 것도 unknown으로 간다!
ClassCastingException 이런 것도!!
내가 못 잡은 에러들은 전부 이쪽으로!!
내가 잡은 에러들은 커스텀 되어있는 쪽으로 직접 던짐!!
그러나… 우리는 지금 공부를 해야하니까, unknown은 생성하지 않는다.
→ 하나하나 다 잡아라!
작동 하는지 잠깐 확인해보자

임시 코드! 작동 되는지 확인만 해보고 지우자!


이 생성자로 가서 치는 것! > super를 잘 모르겠으면 자바 공부를 한 번 더 하자!
super = 자식이 부모 클래스한테 접근할 때 사용. Exception401이 RuntimeException에게 접근 가능 (부모 클래스의 멤버를 호출하거나 재정의)
Share article