Article이 없는 경우, 적절한 에러 페이지가 나오게 하시오.
프로그램 실행 중, 종종 발생하는 예상치 못한 문제. 이를 에러라고 한다. 이러한 에러를 처리하는 기법! 바로 예외(Exception)이다. 특정 문제(Error)가 발생하면, 이와 연관된 예외 객체를 만들어 문제 발생을 알리는 것이다.
가령 영화 등에서 은행 강도 침입 시, 비상 버튼을 누르고, 이를 통해 진압 요원들이 도착하는 장면을 본적이 있을 것이다. 여기서 은행 강도가 침입 하는 사건은 에러(Error ouccurs)가 되고, 비상 버튼을 누르는 것은 예외 객체를 생성(Throwing New Exception)하는 것과 같다. 진압 요원들의 도착은 예외 처리(Exception Handling)에 비유할 수 있다.
에러 처리 담당자를 선언하는 애노테이션. 바로 @ControllerAdvice이다. 참고, @RestControllerAdivce도 있음. 해당 애노테이션이 부여되면, 특정 구역(패키지)의 에러를 감지하고, 이를 처리할 수 있다.
1) 메소드 수정: “controller/ArticleController”
...
@GetMapping("/articles/{id}")
public String show(@PathVariable Long id, Model model) {
// article 가져오기!
Article article = articleRepository.findById(id)
.orElseThrow( // 없다면, 에러 발생!
() -> new IllegalArgumentException("해당 Article이 없습니다.")
);
// article을 뷰 페이지로 전달
model.addAttribute("article", article);
return "articles/show";
}
...
2) 에러처리 컨트롤러 생성: “controller/ExceptionController”
// Spring Boot 전역 에러 처리 - https://springboot.tistory.com/25
// Exception Handling in Spring MVC - https://luvstudy.tistory.com/74
@ControllerAdvice("com.example.myblog.controller") // 해당 패키지 내 모든 에러를 처리!
public class ExceptionController {
@ExceptionHandler(IllegalArgumentException.class) // 해당 예외 발생 시, 수행!
public String notFound(Exception exception, Model model) {
model.addAttribute("exception", exception);
return "errors/404-error"; // 해당 페이지를 보여 줌!
}
}
3) 에러 페이지 생성: “errors/404-error.mustache”
{{>layouts/header}}
<!-- jumbotron -->
<div class="jumbotron">
<h1>404 Not Found</h1>
<hr>
<p>{{exception.message}}</p>
</div>
{{>layouts/footer}}