SpringBoot中干掉Whitelabel Error Page返回自定义内容的实现

2022-07-25,,,,

 1. 引言

springboot中对于错误请求的页面是长这样的,

然而我们在访问在一些网站时,如果请求错误,一般都会有友好美观的提示,比如知乎这个,这比起一堆错误信息要友好的多了。

我们可以根据项目业务来自定义错误请求(requestmapping中没有映射到的请求)的处理,比如返回自定义错误页面或者json字符串。

2. 分析

我们看看springboot中对于错误请求是如何处理的。springboot项目中搜索whitelabel定位到类whitelabelerrorviewconfiguration,可以看到它是errormvcautoconfiguration的一个静态内部类,而且正是这个类处理的错误请求的,代码中的defaulterrorview正是我们看到的默认错误页面。

@configuration(proxybeanmethods = false)
@conditionalonproperty(prefix = "server.error.whitelabel", name = "enabled", matchifmissing = true)
@conditional(errormvcautoconfiguration.errortemplatemissingcondition.class)
protected static class whitelabelerrorviewconfiguration {

	private final errormvcautoconfiguration.staticview defaulterrorview = new errormvcautoconfiguration.staticview();

	@bean(name = "error")
	@conditionalonmissingbean(name = "error")
	public view defaulterrorview() {
		return this.defaulterrorview;
	}
	// and so on...
}

仔细研究这个代码,我们不难发现,我们至少有两种方法可以替换掉默认的实现自定义错误页面。

入手点1:

@conditionalonproperty(prefix = "server.error.whitelabel", name = "enabled", matchifmissing = true)

入手点2:

@bean(name = "error")
@conditionalonmissingbean(name = "error")

3. 尝试

3.1 尝试 1

@conditionalonproperty(prefix = "server.error.whitelabel", name = "enabled", matchifmissing = true)

我们看到server.error.whitelabel.enabled控制了这个类是否装配,我们可以在配置中将其设为false

server:
 error:
  whitelabel:
   enabled: false
  path: /error

该配置类为errorproperties,默认的错误请求为/error,将 whitelabel 禁用后在 controller 中定义请求 /error返回自定义内容

@controller
public class errorcontroller {

	@requestmapping("/error")
	@responsebody
	public r error(httpservletrequest request) {
		integer status = (integer) request.getattribute(requestdispatcher.error_status_code);
		if (objects.nonnull(status)) {
			httpstatus httpstatus = httpstatus.valueof(status);
			return rutils.fail(httpstatus);
		}
		return rutils.fail("error");
	}

}

运行!一顿操作猛如虎,仔细一看原地杵,想法不错,但疯狂报错:

org.springframework.beans.factory.unsatisfieddependencyexception: error creating bean with name 'documentationpluginsbootstrapper' defined in url [jar:file:/d:/environment/maven/repository/io/springfox/springfox-spring-web/2.9.2/springfox-spring-web-2.9.2.jar!/springfox/documentation/spring/web/plugins/documentationpluginsbootstrapper.class]: unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.unsatisfieddependencyexception: error creating bean with name 'webmvcrequesthandlerprovider' defined in url [jar:file:/d:/environment/maven/repository/io/springfox/springfox-spring-web/2.9.2/springfox-spring-web-2.9.2.jar!/springfox/documentation/spring/web/plugins/webmvcrequesthandlerprovider.class]: unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.beancreationexception: error creating bean with name 'requestmappinghandlermapping' defined in class path resource [xxx/xxx/xxx/config/webmvcconfig.class]: invocation of init method failed; nested exception is java.lang.illegalstateexception: ambiguous mapping. cannot map 'basicerrorcontroller' method
org.springframework.boot.autoconfigure.web.servlet.error.basicerrorcontroller#error(httpservletrequest)
to { /error}: there is already 'errorcontroller' bean method

具体报错原因未作分析,怀疑是我项目设置有问题,笔者使用的springboot版本是2.3.6.release,大家可以尝试一些行不行。既然第一个方法尝试接着尝试失败,那就试试第二个吧。

3.2 尝试2

@bean(name = "error")
@conditionalonmissingbean(name = "error")

这个操作更简单,我们只要向ioc 容器中注入一个名为errorbean即可,返回类型为view:

@configuration
public class myconfig {
  @bean("error")
	public view error() {
		modelandview view = new modelandview(new mappingjackson2jsonview());
		return view.getview();
	}
}

其中new mappingjackson2jsonview()返回的json字符串的 view ,当然你也可以根据业务需求灵活使用,如果想获取httpservletrequest可以这样获取,但使用时需要注意判空,因为bean实例化注入是可能获取不到httpservletrequest而造成npe,项目启动失败。

public static httpservletrequest getrequest() {
  return optional.ofnullable(requestcontextholder.getrequestattributes())
     .map(r -> ((servletrequestattributes) r).getrequest())
     .orelse(null);
}

结果当然是没问题的,会返回以下信息:

4. 总结

解决问题:

搜索引擎找解决方法深入源码尝试自己解决

到此这篇关于springboot中干掉whitelabel error page返回自定义内容的文章就介绍到这了,更多相关springboot返回自定义内容内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《SpringBoot中干掉Whitelabel Error Page返回自定义内容的实现.doc》

下载本文的Word格式文档,以方便收藏与打印。