Updated:

1. 개요

스프링에서는 ErrorPage를 자동으로 등록하는데, /error를 기본 에러 페이지 경로로 사용하다. 이번에는 스프링에서 에러 페이지를 설정하는 방법에 대해 알아보도록 하자.

2. 개발 환경

  • Java 11

  • Spring Boot 2.7.5

3. 뷰 선택 우선순위

스프링은 BasicErrorController를 자동으로 등록하여 /error를 매핑에서 처리해주는데, 여러 에러 페이지가 있을 경우 아래와 같은 우선순위로 매핑된다.

1) 뷰 템플릿

  • resources/templates/error/500.html

  • resources/templates/error/5xx.html

2) 정적 리소스 (static, public)

  • resources/static/error/400.html

  • resources/static/error/404.html

  • resources/static/error/4xx.html

3) 적용 대상이 없을 때

  • resources/templates/error.html

4. 예제 코드

[ServletExController.java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Slf4j
@Controller
public class ServletExController {

    @GetMapping("/error-ex")
    public void errorEx() {
        throw new RuntimeException("예외 발생!");
    }

    @GetMapping("/error-400")
    public void error400(HttpServletResponse response) throws IOException {
        response.sendError(400, "400 오류!");
    }

    @GetMapping("/error-404")
    public void error404(HttpServletResponse response) throws IOException {
        response.sendError(404, "404 오류!");
    }

    @GetMapping("/error-500")
    public void error500(HttpServletResponse response) throws IOException {
        response.sendError(500);
    }
}

[resources/template/error/4xx.html]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
</head>
<body>
<div class="container" style="max-width: 600px">
    <div class="py-5 text-center">
        <h2>4xx 오류 화면 스프링 부트 제공</h2> </div>
    <div>
        <p>오류 화면 입니다.</p>
    </div>
    <hr class="my-4">
</div> <!-- /container -->
</body>
</html>

[resources/template/error/404.html]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
</head>
<body>
<div class="container" style="max-width: 600px">
    <div class="py-5 text-center">
        <h2>404 오류 화면 스프링 부트 제공</h2> </div>
    <div>
        <p>오류 화면 입니다.</p>
    </div>
    <hr class="my-4">
</div> <!-- /container -->
</body>
</html>

[resources/template/error/500.html]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
</head>
<body>
<div class="container" style="max-width: 600px">
    <div class="py-5 text-center">
        <h2>500 오류 화면 스프링 부트 제공</h2> </div>
    <div>
        <p>오류 화면 입니다.</p> </div>
    <hr class="my-4">
</div> <!-- /container -->
</body>
</html>

4. 실행 결과

Updated:

Leave a comment