首页 > 解决方案 > 使用 ErrorController 处理 http 错误

问题描述

我正在使用带有 AuthenticationEntryPoint 的 httpBasic 来验证此人是否已通过身份验证。我想通过 ErrorOcntroller 接口发送自定义错误页面。而不是仅仅返回一个字符串。

这是我的代码:

@Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName());
        response.response.sendRedirect("/error");
    }

我的错误控制器类

@Controller
public class RequestErrorController implements ErrorController {

    private static final Logger log = LoggerFactory.getLogger(RequestErrorController.class);
    @RequestMapping("/error")
    public String handleError(HttpServletRequest request) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

        //log.error("Error 404 generated for this request ->"+ request.getRequestURI());
        if (status != null) {
            int statusCode = Integer.parseInt(status.toString());

            if(statusCode == HttpStatus.UNAUTHORIZED.value()) {
                return "error-401";
            }
            if(statusCode == HttpStatus.NOT_FOUND.value()) {
                return "error-404";
            }
            else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                return "error-403";
            }
            else if(statusCode == HttpStatus.BAD_REQUEST.value()) {
                return "The request did not match any end-point. Please revise the request signature and parameters type. ";
            }
            // on va rajouter bad request vue que 500 est deja la
        }
        return "error";
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}

问题是它根本没有到达这个控制器。

我已经对我的代码进行了更新,最后到达了控制器。现在的问题是,它正在寻找 freemake 模板:

2021-08-06 18:03:42,240 INFO [http-nio-8080-exec-2] c.n.j.A.RequestInterceptor [RequestInterceptor.java:122] returning true
0 [http-nio-8080-exec-2] DEBUG freemarker.cache  - Couldn't find template in cache for "error.ftlh"("en_US", UTF-8, parsed); will try to load it.
2 [http-nio-8080-exec-2] DEBUG freemarker.cache  - TemplateLoader.findTemplateSource("error_en_US.ftlh"): Not found
3 [http-nio-8080-exec-2] DEBUG freemarker.cache  - TemplateLoader.findTemplateSource("error_en.ftlh"): Not found
3 [http-nio-8080-exec-2] DEBUG freemarker.cache  - TemplateLoader.findTemplateSource("error.ftlh"): Not found
2021-08-06 18:03:42,272 DEBUG [http-nio-8080-exec-2] o.s.w.f.CommonsRequestLoggingFilter [CommonsRequestLoggingFilter.java:55] REQUEST DATA : GET /error]

标签: javaspringspring-bootfreemarker

解决方案


我发现了一个类似的堆栈讨论 https://stackoverflow.com/a/26221980/16571215

还有另一种似乎很有希望的解决方案。


推荐阅读