如何解决如何在Spring Boot for / error页面中返回自定义错误消息
我有一个Spring Boot项目和一些带有百里香的UI。我设计了一个/ error页面而不是White level错误,并且它按预期工作。但是我需要将一些字符串传递给/ 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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。