首页 文章

Spring Boot删除Whitelabel错误页面

提问于
浏览
127

我正在尝试删除白标错误页面,所以我所做的是为“/ error”创建了一个控制器映射,

@RestController
public class IndexController {

    @RequestMapping(value = "/error")
    public String error() {
        return "Error handling";
    }

}

但现在我收到了这个错误 .

Exception in thread "AWT-EventQueue-0" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource   [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Invocation  of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'basicErrorController' bean method 
public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>>  org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletR equest)
to {[/error],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'indexController' bean method

不知道我做错了什么 . 请指教 .

EDIT:

已经将 error.whitelabel.enabled=false 添加到application.properties文件中,仍然会出现相同的错误

11 回答

  • 30

    您需要将代码更改为以下内容:

    @RestController
    public class IndexController implements ErrorController{
    
        private static final String PATH = "/error";
    
        @RequestMapping(value = PATH)
        public String error() {
            return "Error handling";
        }
    
        @Override
        public String getErrorPath() {
            return PATH;
        }
    }
    

    您的代码不起作用,因为当您没有指定 ErrorController 的实现时,Spring Boot会自动将 BasicErrorController 注册为Spring Bean .

    要查看该事实,只需导航到 ErrorMvcAutoConfiguration.basicErrorController here .

  • 38

    如果你想要一个更“JSONish”的响应页面,你可以试试这样的东西:

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.web.ErrorAttributes;
    import org.springframework.boot.autoconfigure.web.ErrorController;
    import org.springframework.util.Assert;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.context.request.RequestAttributes;
    import org.springframework.web.context.request.ServletRequestAttributes;
    
    import javax.servlet.http.HttpServletRequest;
    import java.util.Map;
    
    @RestController
    @RequestMapping("/error")
    public class SimpleErrorController implements ErrorController {
    
      private final ErrorAttributes errorAttributes;
    
      @Autowired
      public SimpleErrorController(ErrorAttributes errorAttributes) {
        Assert.notNull(errorAttributes, "ErrorAttributes must not be null");
        this.errorAttributes = errorAttributes;
      }
    
      @Override
      public String getErrorPath() {
        return "/error";
      }
    
      @RequestMapping
      public Map<String, Object> error(HttpServletRequest aRequest){
         Map<String, Object> body = getErrorAttributes(aRequest,getTraceParameter(aRequest));
         String trace = (String) body.get("trace");
         if(trace != null){
           String[] lines = trace.split("\n\t");
           body.put("trace", lines);
         }
         return body;
      }
    
      private boolean getTraceParameter(HttpServletRequest request) {
        String parameter = request.getParameter("trace");
        if (parameter == null) {
            return false;
        }
        return !"false".equals(parameter.toLowerCase());
      }
    
      private Map<String, Object> getErrorAttributes(HttpServletRequest aRequest, boolean includeStackTrace) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(aRequest);
        return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace);
      }
    }
    
  • 206

    您可以通过指定完全删除它:

    import org.springframework.context.annotation.Configuration;
    import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
    ...
    @Configuration
    @EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
    public static MainApp { ... }
    

    但请注意,这样做可能会导致servlet容器的whitelabel页面显示:)


    编辑:另一种方法是通过application.yaml . 只需输入值:

    spring:
      autoconfigure:
        exclude: org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
    

    Documentation

    对于Spring Boot <2.0,该类位于包 org.springframework.boot.autoconfigure.web 中 .

  • 28

    Spring boot doc 'was'错了(他们已经修好了):

    要关闭它,您可以设置error.whitelabel.enabled = false

    应该

    要关闭它,您可以设置server.error.whitelabel.enabled = false

  • 10

    手动here表示您必须将 server.error.whitelabel.enabled 设置为 false 才能禁用标准错误页面 . 也许这就是你想要的?

    顺便说一句,我在添加/错误映射后遇到了同样的错误 .

  • 14

    使用Spring Boot> 1.4.x,您可以这样做:

    @SpringBootApplication(exclude = {ErrorMvcAutoConfiguration.class})
    public class MyApi {
      public static void main(String[] args) {
        SpringApplication.run(App.class, args);
      }
    }
    

    但是如果异常,servlet容器将显示自己的错误页面 .

  • 2

    这取决于您的 Spring 季启动版本:

    SpringBootVersion <= 1.2 然后使用 error.whitelabel.enabled = false

    SpringBootVersion> = 1.3 然后使用 server.error.whitelabel.enabled = false

  • 6

    在使用Mustache模板的Spring Boot 1.4.1中,将errors.html放在模板文件夹下就足够了:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="utf-8">
      <title>Error</title>
    </head>
    
    <body>
      <h1>Error {{ status }}</h1>
      <p>{{ error }}</p>
      <p>{{ message }}</p>
      <p>{{ path }}</p>
    </body>
    
    </html>
    

    通过为 /error 创建拦截器可以传递其他变量

  • 5

    这是一种替代方法,它非常类似于_680763中指定错误映射的"old way" .

    只需将其添加到Spring Boot配置中:

    @SpringBootApplication
    public class Application implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
    
        @Override
        public void customize(ConfigurableServletWebServerFactory factory) {
            factory.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/errors/403.html"));
            factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/errors/404.html"));
            factory.addErrorPages(new ErrorPage("/errors/500.html"));
        }
    
    }
    

    然后,您可以正常定义静态内容中的错误页面 .

    如果需要,定制器也可以是单独的 @Component .

  • 1

    server.error.whitelabel.enabled = false

    将上面的行包含在Resources文件夹application.properties中

    更多错误问题解决请参考http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-customize-the-whitelabel-error-page

  • 0

    我试图从微服务调用REST endpoints ,我正在使用resttemplate的 put 方法 .

    在我的设计中,如果REST endpoints 内发生任何错误,它应该返回一个JSON错误响应,它适用于某些调用但不适用于此 put ,它返回了白标错误页面 .

    所以我做了一些调查,我发现了;

    Spring尝试理解调用者,如果它是一台机器,那么它返回JSON响应,或者如果它是浏览器,则返回白标错误页面HTML .

    因此:我的客户端应用程序需要向REST endpoints 说调用者是一台机器,而不是浏览器,因此客户端应用程序需要添加' application/json ' into the ACCEPT header explicitly for the resttemplate' s 'put'方法 . 我将其添加到 Headers 中并解决了问题 .

    我对 endpoints 的调用:

    restTemplate.put(url, request, param1, param2);
    

    对于上面的调用我必须在下面添加 Headers 参数 .

    headers.set("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
    

    或者我也试图改变put to exchange,在这种情况下,交换调用为我添加了相同的 Headers 并解决了问题,但我不知道为什么:)

    restTemplate.exchange(....)
    

相关问题