简体   繁体   中英

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

I have a spring boot project and some UI with thymeleaf. I have designed a /error page instead of the White level error, and it is working as expected. However I need to pass some string to /error and display that string in the error page. I am wondering how to do that.

This is my /error page :

<!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>

Error method :

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

Instead of the error message Sorry! Something went wrong ! Sorry! Something went wrong ! I want to send something specific from the caller. How to do that.

You can do it this way

Template

    <!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";

}

I could find a simple way at last using redirectAttributes.addFlashAttribute .

Here is my some controller method from where I am redirecting the /error with reason :

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

Ans here is my error page :

    <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM