1. 에러 페이지 화면 만들기

err/400.mustache
{{> /layout/header}}
<div class="container my-3">
<h1>BadRequest 400</h1>
<hr>
<h41>{{msg}}</h41>
</div>
{{> /layout/footer}}
err/401.mustache 인증안됨
{{> /layout/header}}
<div class="container my-3">
<h1>Unauthorized 401</h1>
<hr>
<h41>{{msg}}</h41>
</div>
{{> /layout/footer}}
err/403.mustache 권한없음
{{> /layout/header}}
<div class="container my-3">
<h1>Forbidden 403</h1>
<hr>
<h41>{{msg}}</h41>
</div>
{{> /layout/footer}}
err/404.mustache
{{> /layout/header}}
<div class="container my-3">
<h1>Not Found 404</h1>
<hr>
<h41>{{msg}}</h41>
</div>
{{> /layout/footer}}
err/500.mustache
{{> /layout/header}}
<div class="container my-3">
<h1>Server Error 500</h1>
<hr>
<h41>{{msg}}</h41>
</div>
{{> /layout/footer}}
2. 핸들러 만들기
_core/err/MyExceptionHandler

모두 RundimeEception 이기 때문에 오류가 남. 그래서 커스텀익셉션을 만들어서 상속받는 구조를 만든다.
package shop.mtcoding.blog._core.err.exception;
public class Exception400 extends RuntimeException{
public Exception400(String msg) {
super(msg);
}
}

에러 컨트롤러 및 커스텀 익셉션 만들
@ControllerAdvice //runtimeException 이 터지만 해당 파일로 오류가 모인다.
public class MyExeptionHandler{
@ExceptionHandler(Exception400.class)
public String ex400(RuntimeException e){
request.setAttribute("msg",e.getMessage());
return "err/400";
}
@ExceptionHandler(Exception401.class)
public String ex401(RuntimeException e, HttpServletRequest request){
request.setAttribute("msg",e.getMessage());
return "err/401";
}
@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";
}
}
@GetMapping("/user/update-form")
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";
}

로그인 하지 않으면 401 페이지로 throw 된다.
Share article