Spring Boot 定制错误页面/错误数据

1. springboot 默认错误处理

浏览器访问,返回一个默认的错误页面
在这里插入图片描述
其他客户端访问,默认响应一个json数据

springboot中的错误处理自动配置:

org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({
    Servlet.class, DispatcherServlet.class })
// Load before the main WebMvcAutoConfiguration so that the error View is available
@AutoConfigureBefore(WebMvcAutoConfiguration.class)
@EnableConfigurationProperties({
    ServerProperties.class, ResourceProperties.class,
		WebMvcProperties.class })
public class ErrorMvcAutoConfiguration {
   
	@Bean
	@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
	public DefaultErrorAttributes errorAttributes() {
   
		return new DefaultErrorAttributes(
				this.serverProperties.getError().isIncludeException());
	}
	//处理错误请求,没有配置的时候默认处理/error请求
	@Bean
	@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
	public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
   
		return new BasicErrorController(errorAttributes, this.serverProperties.getError(),
				this.errorViewResolvers);
	}
	//系统出现错误以后来到error请求进行处理(web.xml注册错误页面)
	//注册错误页面响应规则
	@Bean
	public ErrorPageCustomizer errorPageCustomizer() {
   
		return new ErrorPageCustomizer(this.serverProperties, this.dispatcherServletPath);
	}

	@Configuration
	static class DefaultErrorViewResolverConfiguration {
   

		private final ApplicationContext applicationContext;

		private final ResourceProperties resourceProperties;

		DefaultErrorViewResolverConfiguration(ApplicationContext applicationContext,
				ResourceProperties resourceProperties) {
   
			this.applicationContext = applicationContext;
			this.resourceProperties = resourceProperties;
		}

		@Bean
		@ConditionalOnBean(DispatcherServlet.class)
		@ConditionalOnMissingBean
		public DefaultErrorViewResolver conventionErrorViewResolver() {
   
			return new DefaultErrorViewResolver(this.applicationContext,
					this.resourceProperties);
		}

	}

	private static class ErrorPageCustomizer implements ErrorPageRegistrar, Ordered {
   

		private final ServerProperties properties;

		private final DispatcherServletPath dispatcherServletPath;

		protected ErrorPageCustomizer(ServerProperties properties,
				DispatcherServletPath dispatcherServletPath) {
   
			this.properties = properties;
			this.dispatcherServletPath = dispatcherServletPath
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值