스프링 부트는 ErrorPage라는 기본 오류 페이지(기본경로 : /error)와 이를 컨트롤 할 수 있는 BasicErrorController라는 스프링 컨트롤러를 자동으로 등록한다.
개발자는 오직 BasicErrorController가 제공하는 규칙과 우선순위에 따라서 오류 페이지 화면만 등록하면 된다.
BasicErrorController의 처리 순서는 아래와 같다. 아래 해당 경로에 원하는 view 파일을 넣어두기만 하면 된다. (위에서 아래로 내려갈수록 우선순위가 낮아진다.)
BasicErrorController 컨트롤러는 다음 정보를 model에 담아서 view에 전달한다.
주의 : 이러한 오류 관련 정보들을 고객에게 그대로 노출하는 것은 보안상 문제가 될 수 있기 때문에, 설정을 통해 BasicErrorController에서 오류 정보들을 model에 담을 것인지 선택 할 수 있다.
server.error.include-exception=true
// 값으로 never, always, on_param을 입력할 수 있다.
// never : 노출하지 않음
// always : 항상 노출
// on_param : 파라미터가 있을 때만 노출
#server.error.include-message=never
#server.error.include-stacktrace=never
#server.error.include-binding-errors=never
@GetMapping("/profile/{nickname}")
public String viewProfile(@PathVariable String nickname, Model model, HttpServletResponse response, @CurrentUser Account account) throws IOException {
Account byNickname = accountRepository.findByNickname(nickname);
if (byNickname == null) {
response.sendError(404, nickname + "에 해당하는 사용자가 없습니다.");
return "error";
}
...
return "account/profile";
}
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head th:replace="fragments.html :: head"></head>
<body class="bg-light">
<div class="container">
<div class="py-5 text-center">
<h2 th:text="${message}">errorMessage</h2>
</div>
</div>
</body>
</html>
에러 공통 처리 컨트롤러의 기능을 변경하고 싶으면 ErrorController 인터페이스를 상속 받아서 구현하거나, BasicErrorController를 상속 받아서 기능을 추가할 수 있다.
참조
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-2