Spring Boot删除Whitelabel错误页面

Yas*_*aka 146 spring spring-boot

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

@RestController
public class IndexController {

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

}
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

编辑:

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

geo*_*and 228

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

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

要看到这个事实,只需导航到ErrorMvcAutoConfiguration.basicErrorController 这里.

  • 我不得不通过源来找到这个:-) (4认同)
  • 嗯,是的,再次感谢!起初我不知道如何获得`ErrorAttributes`对象(包含错误详细信息),但后来我尝试简单地@Autowiring它,它的工作原理.我现在一起去的地方:https://gist.github.com/jonikarppinen/662c38fb57a23de61c8b (3认同)

aco*_*hen 43

如果你想要一个更"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);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 在Spring-Boot v2中,ErrorController和ErrorAttributes类在org.springframework.boot.web.servlet.error包中,并且ErrorAttributes#getErrorAttributes方法签名已经更改,请注意对Spring-Boot v1的依赖,并可能给出v2的提示,谢谢. (6认同)
  • 考虑到上面的评论的 SimpleErrorController.java 的更新版本可以在这里找到 &gt; https://gist.github.com/oscarnevarezleal/24030102adbe5dd43d9d53727feacc45 (3认同)
  • 更改:私有 Map&lt;String, Object&gt; getErrorAttributes(HttpServletRequest aRequest, boolean includeStackTrace) { RequestAttributes requestAttributes = new ServletRequestAttributes(aRequest); 返回 errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace); 由:私有地图&lt;字符串,对象&gt; getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) { WebRequest webRequest = new ServletWebRequest(request); 返回 this.errorAttributes.getErrorAttributes(webRequest, includeStackTrace); } (2认同)

wil*_*ome 36

Spring boot doc ''错了(他们已修复它):

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

应该

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

  • 这将禁用白标签错误页面,但 Spring Boot 无论如何都会映射端点“/error”。要释放端点“/error”,请设置“server.error.path=/error-spring”或其他路径。 (4认同)

hoo*_*man 31

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

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

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


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

spring:
  autoconfigure:
    exclude: org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
Run Code Online (Sandbox Code Playgroud)

文档

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


Inn*_*ker 15

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

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

  • 这将禁用白标签错误页面,但 Spring Boot 无论如何都会映射端点“/error”。要释放端点“/error”,请设置“server.error.path=/error-spring”或其他路径。 (2认同)

db8*_*b80 11

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

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

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


sen*_*982 7

这取决于你的春季靴子版本:

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

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


小智 5

在使用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>
Run Code Online (Sandbox Code Playgroud)

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


DJ *_*use 5

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

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

首先,我创建了一个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;
    }
}
Run Code Online (Sandbox Code Playgroud)

其次,我创建了一个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
}
Run Code Online (Sandbox Code Playgroud)

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

server.error.whitelabel.enabled=false
Run Code Online (Sandbox Code Playgroud)

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