Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring引导不会显示实现自定义ErrorController的错误页面_Spring_Spring Boot_Spring Mvc_Error Handling_Thymeleaf - Fatal编程技术网

Spring引导不会显示实现自定义ErrorController的错误页面

Spring引导不会显示实现自定义ErrorController的错误页面,spring,spring-boot,spring-mvc,error-handling,thymeleaf,Spring,Spring Boot,Spring Mvc,Error Handling,Thymeleaf,我试图根据HTTP状态代码显示自定义错误页。我所做的是在CustomErrorController中实现Spring的ErrorController接口,但Spring Boot似乎无法识别它 我已经按照本教程完成了:第3.1节 在这里,我已经读到,首先你需要摆脱著名的Spring默认的白标签错误页面。所以我这样做了: @SpringBootApplicationexclude={ErrorMvcAutoConfiguration.class} 公共类MyApplication{ 公共静态无效字

我试图根据HTTP状态代码显示自定义错误页。我所做的是在CustomErrorController中实现Spring的ErrorController接口,但Spring Boot似乎无法识别它

我已经按照本教程完成了:第3.1节

在这里,我已经读到,首先你需要摆脱著名的Spring默认的白标签错误页面。所以我这样做了:

@SpringBootApplicationexclude={ErrorMvcAutoConfiguration.class} 公共类MyApplication{ 公共静态无效字符串[]args{ SpringApplication.runMyApplication.class,args; } } 这似乎是可行的,因为白标签错误页面已经不再出现了,但是现在当错误发生时,ApacheTomcat错误页面会出现,其中包含堆栈跟踪,而不是我的错误页面

然后我刚刚实现了CustomErrorController,如下所示:

@控制器 @请求映射/错误 公共类CustomErrorController实现ErrorController{ @请求映射 公共字符串handleErrorHttpServletRequest请求{ Integer statusCode=Integer request.getAttributeRequestDispatcher.ERROR\u STATUS\u CODE; 如果statusCode!=null{ //特定错误页 返回重定向:/error/+statusCode; } //全局错误页 返回错误/错误; } @凌驾 公共字符串getErrorPath{ 返回/错误; } @GetMapping/404 公共字符串notFoundErrorPage{ 返回错误/404; } //其他错误代码映射方法 } 我使用的是Thymeleaf,我的错误视图位于src/main/resources/views/error下,其中每个特定的错误页面名称都遵循建议的.html格式,因此,例如,404错误将与404.html页面关联

到目前为止,我还没有遇到其他应用程序视图的问题。实际上,我已经将我的Spring安全性配置为在发生拒绝访问且错误页面正确显示时调用/error/403端点

对于/error/500也会发生同样的情况,因为我还实现了以下@ControllerAdvice@ExceptionHandler方法,所以在发生内部服务器异常时调用该方法:

@控制器建议 @Log4j2 公共类GlobalDefaultExceptionHandler{ @ExceptionHandlerException.class 公共字符串defaultErrorHandlerException异常引发异常{ 如果AnnotationUtils.FindAnotationException.getClass、ResponseStatus.class!=null{ 抛出异常; } log.catchingexception; 返回重定向:/error/500; } } 那么,如果这些端点中的每一个都单独工作,为什么如果Spring抛出错误,就永远不会调用handleError方法呢

谢谢。

似乎您的GlobalDefaultExceptionHandler正在预先捕获每个异常。这就是为什么handleError从未被调用

您的其他端点可以工作,因为您直接调用它们——正如您所描述的那样

我建议使用@ControllerAdvice来处理特定的异常,并让CustomErrorController实现处理所有尚未处理的异常。Spring boot将它们包装在Http状态为500的NestedServletException中。您可以通过以下方法获得handleError内部的根本原因:

查看这些答案,了解有关订购和spring boot中错误工作流程的更多信息:

Object exception = request.getAttribute("javax.servlet.error.exception");
    if (String.valueOf(exception) != null) {
        log.info("Nested Exception: " + String.valueOf(exception));
    }