首页 > 解决方案 > Thymeleaf + SpringBoot:在错误页面中显示错误

问题描述

我有一个带有 Thymeleaf 的 SpringBoot v2.3.7.RELEASE。我创建了这个模板来查看错误,但是当应用程序中出现异常时,我在源代码中看不到任何异常:

    <div class="jumbotron text-center">

        <h1>Uh-oh! Something Happened!</h1>
        <!--  As we are using Thymeleaf, you might consider using
              ${#httpServletRequest.requestURL}. But that returns the path
              to this error page.  Hence we explicitly add the url to the
              Model in some of the example code. -->
        <p th:if="${url}">
            <b>Page:</b> <span th:text="${url}">Page URL</span>
        </p>

        <p th:if="${timestamp}" id='created'>
            <b>Occurred:</b> <span th:text="${timestamp}">Timestamp</span>
        </p>


        <p>Support may ask you to right click to view page source.</p>

        <!--
          // Hidden Exception Details  - this is not a recommendation, but here is
          // how you hide an exception in the page using Thymeleaf
          -->
        <div th:utext="'&lt;!--'" th:remove="tag"></div>
        <div th:utext="'Failed URL: ' +  ${url}" th:remove="tag">${url}</div>
        <div th:utext="'Exception: ' + ${exception}" th:remove="tag">${exception}</div>
        <ul th:remove="tag">
            <li th:each="ste : ${exception}" th:remove="tag"><span
                    th:utext="${ste}" th:remove="tag">${ste}</span></li>
        </ul>
        <div th:utext="'--&gt;'" th:remove="tag"></div>

    </div>

</div>

和控制器:

@Controller
public class MyErrorController implements ErrorController {

    private final static String PATH = "/error";

    @RequestMapping(PATH)
    public String getErrorPath() {
        return "error/genericError";
    }


}

标签: javaspringspring-bootspring-mvcthymeleaf

解决方案


  1. Spring Boot 默认提供 /error 映射,所有异常/错误都被转发。对于 Thymeleaf(或其他模板引擎),我们可以将错误映射到 src/main/resources/templates/ 目录下名为 'error' 的全局自定义模板文件。

  2. 启用堆栈跟踪作为 Thymeleaf 视图的表达式属性:

    server.error.include-stacktrace=总是


推荐阅读