在我的SpringBoot项目中,我有一个CustomErrorController,它映射到“/error”。但是由于某种原因,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确实提供了此功能?
编辑2:
上面的代码可以正常工作,以防其他人偶然发现同一问题。
最佳答案
您要执行的操作无法通过请求映射完成。
您可以使用一些异常处理解决方案,在这里可以找到一些示例:
https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
关于spring - Spring忽略了我的CustomErrorController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49555927/