Search code examples
javaspring-bootthymeleafmicroservicescustom-error-pages

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 ! I want to send something specific from the caller. How to do that.


Solution

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