如何 return 在 Spring Boot for /error 页面中自定义错误消息

How to return custom error message in Spring Boot for /error page

我有一个 spring 启动项目和一些 UI with thymeleaf。我设计了一个 /error 页面而不是白色级别的错误,它按预期工作。但是我需要将一些字符串传递给 /error 并在错误页面中显示该字符串。我想知道该怎么做。

这是我的 /错误 页面:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Error Occurred.</title>
<link rel="stylesheet" type="text/css" th:href="@{/css/styles.css}">
</head>

<body>    
    <th:block th:include="/_header"></th:block>
    <th:block th:include="/menu"></th:block>

    <div class="page-title">Error!</div>
    <h3 style="color: red;">Sorry! Something went wrong !</h3>    
</body>
</html>

错误方法:

@RequestMapping("/error")
public String error() {
    logger.info("Error Page called...");
    return "error";
}

我不想发送错误消息 Sorry! Something went wrong !,而是想从呼叫者那里发送一些特定的信息。怎么做。

你可以这样做

模板

    <!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Error Occurred.</title>
<link rel="stylesheet" type="text/css" th:href="@{/css/styles.css}">
</head>

<body>    
    <th:block th:include="/_header"></th:block>
    <th:block th:include="/menu"></th:block>

    <div class="page-title">Error!</div>
    <h3 style="color: red;" th:text="${errorMsg}">Sorry! Something went wrong !</h3>    
</body>
</html>



//  Controller
 @RequestMapping("/error")
public String error() {
    logger.info("Error Page called...");
    mmodel.addAttribute("errorMsg", "Custom Error Message");
    return "error";

}

我终于找到了一个简单的方法 redirectAttributes.addFlashAttribute

这是我的一些控制器方法,我从那里重定向 /error,原因是:

String errorMsg = "Cart is Empty. Add some products to Cart." ;
CustomErrorMessage error = new CustomErrorMessage(errorMsg);
redirectAttributes.addFlashAttribute("errorForm", error);
return "redirect:/error";

答案是我的 error 页面:

    <div class="page-title">
        <h3 style="color: red">Sorry! Something went wrong !</h3>
        <th:block th:if="${errorForm == null}">
            <h4>Go to Home Page : <a th:href="@{/}">Home</a></h4>
        </th:block>
        <th:block th:if="${errorForm != null}">
            <div><ul><li>Error reason : <span th:utext="${errorForm.errorMsg}"></span></li></ul></div>
            <h4>Go to Home Page : <a th:href="@{/}">Home</a></h4>               
        </th:block>
    </div>