Spring忽略了我的CustomErrorController

时间:2018-03-29 12:20:30

标签: spring spring-mvc spring-boot error-handling thymeleaf

在我的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重命名为其他内容时,会显示一个whitelabel错误页面,其中显示/ error没有默认映射,这很奇怪,因为我的CustomErrorController确实提供了这个?

EDIT2:

以上代码正常运行,以防万一其他人遇到同样的问题。

1 个答案:

答案 0 :(得分:0)

您尝试做的事情可以通过请求映射来完成。 您可以使用一些异常处理解决方案,在这里您可以找到一些示例:

https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc