Spring

[Spring Boot] Thymeleaf 사용 시 표준 에러페이지 구현

무커 2023. 3. 17. 18:39
728x90
반응형

Spring Boot에서 Thymeleaf를 사용할 때 기본적인 에러 페이지를 구현하는 방법은 다음과 같습니다.

 

1. src/main/resources/templates 디렉토리에 error.html 파일을 생성합니다. 이 파일은

    Spring Boot의 내장된 템플릿 엔진인 Thymeleaf에서 자동으로 인식되어 에러페이지로 사용됩니다.

2. error.html 파일에 다음과 같이 Thymeleaf 문법을 사용하여 에러 정보를 출력합니다.

<!DOCTYPE html>
<html>
<head>
    <title>Error</title>
</head>
<body>
    <h1>Error</h1>
    <p th:text="${status}"></p>
    <p th:text="${error}"></p>
    <p th:text="${message}"></p>
</body>
</html>

3. 이제 애플리케이션에서 에러가 발생하면, Spring Boot는 자동으로 error.html 파일을

    렌더링하고, 에러 정보를 Thymeleaf 문법을 통해 출력합니다.

4. 추가로, 커스텀 에러 페이지를 사용하려면, @ControllerAdvice 어노테이션과

    @ExceptionHandler 어노테이션을 사용하여 컨트롤러를 만들어서 처리할 수 있습니다.

    이를 통해, 에러 타입별로 커스텀 에러 페이지를 제공할 수 있습니다.

 

예를 들어, 다음과 같이 NotFoundException에 대한 커스텀 에러 페이지를 만들 수 있습니다.

@ControllerAdvice
public class CustomErrorController {

    @ExceptionHandler(NotFoundException.class)
    public String handleNotFoundException(Model model) {
        model.addAttribute("status", HttpStatus.NOT_FOUND.value());
        model.addAttribute("error", "Not Found");
        model.addAttribute("message", "The requested resource was not found");
        return "not-found";
    }
}

위의 예제에서 not-found.html은 커스텀 에러 페이지 템플릿 파일이며, handleNotFoundException 메소드에서는 Model을 이용해 에러 정보를 전달합니다. 

이제 NotFoundException이 발생하면, Spring Boot는 not-found.html 파일을 렌더링하고, handleNotFoundException 메소드에서 전달한 에러 정보를 출력합니다.

 

더 간단한 방법이 있습니다.

Thymeleaf에서는 src/main/resources/templates/error/ 경로에 404.html을 생성하면 404에러가 발생할 경우 해당 페이지가 나타납니다. 400, 404 등을 한 번에 하고 싶다면 4xx.html 이렇게 해도 됩니다.

다만, 404.html이 존재할 경우 404.html이 우선순위가 높아 4xx.html이 호출되지 않습니다.

728x90
반응형