Spring Boot 删除白标错误页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25356781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:00:22  来源:igfitidea点击:

Spring Boot Remove Whitelabel Error Page

springspring-boot

提问by Yasitha Chinthaka

I'm trying to remove white label error page, so what I've done was created a controller mapping for "/error",

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

@RestController
public class IndexController {

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

}

But now I"m getting this error.

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

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

Don't know whether I'm doing anything wrong. Please advice.

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

EDIT:

编辑:

Already added error.whitelabel.enabled=falseto application.properties file, still getting the same error

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

回答by geoand

You need to change your code to the following:

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

@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;
    }
}

Your code did not work, because Spring Boot automatically registers the BasicErrorControlleras a Spring Bean when you have not specified an implementation of ErrorController.

您的代码不起作用,因为BasicErrorController当您没有指定ErrorController.

To see that fact just navigate to ErrorMvcAutoConfiguration.basicErrorControllerhere.

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

回答by acohen

If you want a more "JSONish" response page you can try something like that:

如果你想要一个更“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);
  }
}

回答by willome

Spring boot doc'was' wrong (they have since fixed it) :

Spring Boot 文档“错了”(他们已经修复了它):

To switch it off you can set error.whitelabel.enabled=false

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

should be

应该

To switch it off you can set server.error.whitelabel.enabled=false

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

回答by hoodieman

You can remove it completely by specifying:

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

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

However, do note that doing so will probably cause servlet container's whitelabel pages to show up instead :)

但是,请注意,这样做可能会导致 servlet 容器的白标签页面显示出来 :)



EDIT: Another way to do this is via application.yaml. Just put in the value:

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

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

Documentation

文档

For Spring Boot < 2.0, the class is located in package org.springframework.boot.autoconfigure.web.

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

回答by Innot Kauker

Manual heresays that you have to set server.error.whitelabel.enabledto falseto disable the standard error page. Maybe it is what you want?

手册在这里说,你必须设置server.error.whitelabel.enabledfalse禁用标准错误页面。也许这就是你想要的?

I am experiencing the same error after adding /error mapping, by the way.

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

回答by db80

With Spring Boot > 1.4.x you could do this:

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

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

but then in case of exception the servlet container will display its own error page.

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

回答by sendon1982

This depends on your spring boot version:

这取决于您的 Spring Boot 版本:

When SpringBootVersion<= 1.2then use error.whitelabel.enabled = false

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

When SpringBootVersion>= 1.3then use server.error.whitelabel.enabled = false

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

回答by Ecmel Ercan

In Spring Boot 1.4.1 using Mustache templates, placing error.html under templates folder will be enough:

在使用 Mustache 模板的 Spring Boot 1.4.1 中,将 error.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>

Additional variables can be passed by creating an interceptor for /error

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

回答by rustyx

Here's an alternative method which is very similar to the "old way" of specifying error mappings in web.xml.

这是一种替代方法,它与在web.xml.

Just add this to your Spring Boot configuration:

只需将其添加到您的 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"));
    }

}

Then you can define the error pages in the static content normally.

然后就可以正常定义静态内容中的错误页面了。

The customizer can also be a separate @Component, if desired.

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

回答by DJ House

I am using Spring Boot version 2.1.2 and the errorAttributes.getErrorAttributes()signature didn't work for me (in acohen's response). I wanted a JSON type response so I did a little digging and found this method did exactly what I needed.

我使用的是 Spring Boot 2.1.2 版,但errorAttributes.getErrorAttributes()签名对我不起作用(在 acohen 的回应中)。我想要一个 JSON 类型的响应,所以我做了一些挖掘,发现这个方法正是我需要的。

I got most of my information from this thread as well as this blog post.

我从这个线程以及这篇博客文章中获得了我的大部分信息。

First, I created a CustomErrorControllerthat Spring will look for to map any errors to.

首先,我创建了一个CustomErrorControllerSpring 将寻找的将任何错误映射到的对象。

package com.example.error;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
public class CustomErrorController implements ErrorController {

    private static final String PATH = "error";

    @Value("${debug}")
    private boolean debug;

    @Autowired
    private ErrorAttributes errorAttributes;

    @RequestMapping(PATH)
    @ResponseBody
    public CustomHttpErrorResponse error(WebRequest request, HttpServletResponse response) {
        return new CustomHttpErrorResponse(response.getStatus(), getErrorAttributes(request));
    }

    public void setErrorAttributes(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }

    private Map<String, Object> getErrorAttributes(WebRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.putAll(this.errorAttributes.getErrorAttributes(request, this.debug));
        return map;
    }
}

Second, I created a CustomHttpErrorResponseclass to return the error as JSON.

其次,我创建了一个CustomHttpErrorResponse类以将错误返回为 JSON。

package com.example.error;

import java.util.Map;

public class CustomHttpErrorResponse {

    private Integer status;
    private String path;
    private String errorMessage;
    private String timeStamp;
    private String trace;

    public CustomHttpErrorResponse(int status, Map<String, Object> errorAttributes) {
        this.setStatus(status);
        this.setPath((String) errorAttributes.get("path"));
        this.setErrorMessage((String) errorAttributes.get("message"));
        this.setTimeStamp(errorAttributes.get("timestamp").toString());
        this.setTrace((String) errorAttributes.get("trace"));
    }

    // getters and setters
}

Finally, I had to turn off the Whitelabel in the application.propertiesfile.

最后,我不得不关闭application.properties文件中的白标。

server.error.whitelabel.enabled=false

This should even work for xmlrequests/responses. But I haven't tested that. It did exactly what I was looking for since I was creating a RESTful API and only wanted to return JSON.

这甚至应该适用于xml请求/响应。但我没有测试过。它完全符合我的要求,因为我正在创建一个 RESTful API 并且只想返回 JSON。