【问题标题】:Spring ignores my CustomErrorControllerSpring 忽略了我的 CustomErrorController
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢 Vitalii,我创建了一个抛出 404 的异常,它实际上正在工作,我确实需要取消注释 th:action="@{/error}" 而不是指定请求映射方法。
    猜你喜欢
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    • 2014-04-06
    • 2016-02-23
    • 2011-12-22
    • 2017-12-09
    相关资源
    最近更新 更多