【发布时间】:2018-09-08 09:40:36
【问题描述】:
在我的 SpringBoot 项目中,我有一个映射到“/error”的 CustomErrorController。但是出于某种原因,Spring 直接进入了 error.html 页面。我读过 SpringBoot 会在出现时自动转到 error.html 页面,但我希望它通过我的 CustomErrorController 添加客户 errorMsg:
public class CustomErrorController implements ErrorController {
private static final String PATH = "/error";
@RequestMapping(value = PATH)
public ModelAndView renderErrorPage(HttpServletRequest httpRequest) {
System.out.println("In the ErrorController");
ModelAndView errorPage = new ModelAndView("error");
String errorMsg = "";
int httpErrorCode = getErrorCode(httpRequest);
switch (httpErrorCode) {
case 400: {
errorMsg = "Http Error Code: 400. Bad Request";
break;
}
case 401: {
errorMsg = "Http Error Code: 401. Unauthorized";
break;
}
case 404: {
errorMsg = "Http Error Code: 404. Resource not found";
break;
}
case 405: {
errorMsg = "Http Error Code: 405. User not found";
break;
}
case 500: {
errorMsg = "Http Error Code: 500. Internal Server Error";
break;
}
default: {
errorMsg = "Something broke";
}
}
errorPage.addObject("errorMsg", errorMsg);
return errorPage;
}
private int getErrorCode(HttpServletRequest httpRequest) {
return (Integer) httpRequest
.getAttribute("javax.servlet.error.status_code");
}
@Override
public String getErrorPath() {
return PATH;
}
}
我正在使用这个方法抛出异常:
@RequestMapping(value = "/forgot", method = RequestMethod.POST)
public ModelAndView processForgotPasswordForm(ModelAndView modelAndView,
@RequestParam("email") String userEmail) throws NotFoundException,
IOException {
// Gebruiker opzoeken in de datebase
User user = userService.findByEmail(userEmail);
if (user == null) {
throw new NotFoundException("User Not Found");
这是我的 error.html 页面:
<div class="container">
<div th:action="@{/error}">
<h1>ERRORMESSAGE</h1>
<p th:text="${errorMsg}"></p>
</div>
这会导致显示 error.hmtl 页面,但仅显示 ERRORMESSAGE,不会显示 errorMsg,但这可能是因为我的 CustomErrorController 被跳过了。
编辑:
一些附加信息,当我将 error.html 重命名为其他名称时,会显示一个白标签错误页面,显示 /error 没有默认映射,这很奇怪,因为我的 CustomErrorController 确实提供了这个?
EDIT2:
上面的代码可以正常工作,以防其他人偶然发现同样的问题。
【问题讨论】:
标签: spring spring-mvc spring-boot error-handling thymeleaf