SpringBoot之自定义启动异常堆栈信息打印方式

 更新时间:2021年08月09日 08:38:52   作者:weixin_36276193  
这篇文章主要介绍了SpringBoot之自定义启动异常堆栈信息打印方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

在SpringBoot项目启动过程中,当一些配置或者其他错误信息会有一些的规范的提示信息

***************************
APPLICATION FAILED TO START
***************************

Description:

Web server failed to start. Port 8080 was already in use.

Action:

Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.

在SpringBoot 中其实现原理是什么,我们该如何自定义异常信息呢

1、SpringBoot异常处理的源码分析

在springboot启动的核心方法run中会加载所有的SpringBootExceptionReporter

 exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
     new Class[] { ConfigurableApplicationContext.class }, context);

调用了getSpringFactoriesInstances方法

private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
  ClassLoader classLoader = getClassLoader();
  // Use names and ensure unique to protect against duplicates
  Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
  List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
  AnnotationAwareOrderComparator.sort(instances);
  return instances;
 }

其主要通过Spring的Factories机制来加载

public ConfigurableApplicationContext run(String... args) {
  StopWatch stopWatch = new StopWatch();
  stopWatch.start();
  ConfigurableApplicationContext context = null;
  Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
  configureHeadlessProperty();
  SpringApplicationRunListeners listeners = getRunListeners(args);
  listeners.starting();
  try {
   ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
   ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
   configureIgnoreBeanInfo(environment);
   Banner printedBanner = printBanner(environment);
   context = createApplicationContext();
   exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
     new Class[] { ConfigurableApplicationContext.class }, context);
   prepareContext(context, environment, listeners, applicationArguments, printedBanner);
   refreshContext(context);
   afterRefresh(context, applicationArguments);
   stopWatch.stop();
   if (this.logStartupInfo) {
    new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
   }
   listeners.started(context);
   callRunners(context, applicationArguments);
  }
  catch (Throwable ex) {
  //异常捕获中,向用户打印异常信息
   handleRunFailure(context, ex, exceptionReporters, listeners);
   throw new IllegalStateException(ex);
  }

  try {
   listeners.running(context);
  }
  catch (Throwable ex) {
   handleRunFailure(context, ex, exceptionReporters, null);
   throw new IllegalStateException(ex);
  }
  return context;
 }

在try catch中,catch会打印异常信息

private void handleRunFailure(ConfigurableApplicationContext context, Throwable exception,
   Collection<SpringBootExceptionReporter> exceptionReporters, SpringApplicationRunListeners listeners) {
  try {
   try {
    handleExitCode(context, exception);
    if (listeners != null) {
     listeners.failed(context, exception);
    }
   }
   finally {
    reportFailure(exceptionReporters, exception);
    if (context != null) {
     context.close();
    }
   }
  }
  catch (Exception ex) {
   logger.warn("Unable to close ApplicationContext", ex);
  }
  ReflectionUtils.rethrowRuntimeException(exception);
 }
 private void reportFailure(Collection<SpringBootExceptionReporter> exceptionReporters, Throwable failure) {
  try {
   for (SpringBootExceptionReporter reporter : exceptionReporters) {
    if (reporter.reportException(failure)) {
     registerLoggedException(failure);
     return;
    }
   }
  }
  catch (Throwable ex) {
   // Continue with normal handling of the original failure
  }
  if (logger.isErrorEnabled()) {
   logger.error("Application run failed", failure);
   registerLoggedException(failure);
  }
 }

遍历exceptionReporters,打印日常信息

SpringBootExceptionReporter-

SpringBootExceptionReporter是一个回调接口,用于支持对SpringApplication启动错误的自定义报告。里面就一个报告启动失败的方法。

其实现类:org.springframework.boot.diagnostics.FailureAnalyzers

用于触发从spring.factories加载的FailureAnalyzer和FailureAnalysisReporter实例。

2、如何自定义异常信息

/**
 * <p>
 *
 * <p>
 *
 * @author: xuwd
 * @time: 2020/11/16 10:52
 */
public class WannaStopException extends RuntimeException {
}

自定义异常信息打印

public class StopFailureAnalyzer
        extends AbstractFailureAnalyzer<WannaStopException> {
    @Override
    protected FailureAnalysis analyze(Throwable rootFailure, WannaStopException cause) {
        for (StackTraceElement stackTraceElement : cause.getStackTrace()) {
            if (stackTraceElement.getClassName().equals("com.pigx.demo.Config21")) {
                return new FailureAnalysis("A想停止", "别要A了", cause);
            }
        }
        return null;
    }
}

接下来令他生效,通过上面分析可以可看出需要通过AutoConfigurationImportSelector,类似于自定义SpringBoot Starter AutoConfiguration的形式,我们需要在META-INF/spring.factories文件内进行定义,如下所示:

https://juejin.im/post/6844903956208943111

接着在合适的地方抛出WannaStopException 异常

总结

在springboot 启动过程中会先对异常信息进行补捕获,对进行日志格式处理的日志进行处理;其核心是通过SpringBootExceptionReporter回调及sping-spi bean的管理。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • SpringSecurity实现图形验证码功能的实例代码

    SpringSecurity实现图形验证码功能的实例代码

    Spring Security 的前身是 Acegi Security ,是 Spring 项目组中用来提供安全认证服务的框架。这篇文章主要介绍了SpringSecurity实现图形验证码功能,需要的朋友可以参考下
    2018-10-10
  • 关于Java Interface接口的简单练习题

    关于Java Interface接口的简单练习题

    这篇文章主要给大家分享的是关于Java Interface接口的简单练习题,难度不算大,但是要有一个清晰的逻辑建立接口和链接Java类。下面来看看文章的详细介绍吧,需要的朋友可以参考一下
    2021-11-11
  • springMVC之HandlerExceptionResolver使用

    springMVC之HandlerExceptionResolver使用

    这篇文章主要介绍了springMVC之HandlerExceptionResolver使用,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • mybatis-plus条件构造器的操作代码

    mybatis-plus条件构造器的操作代码

    mybatis-plus提供了AbstractWrapper抽象类,提供了很多sql语法支持的方法,比如模糊查询,比较,区间,分组查询,排序,判断空,子查询等等,方便我们用面向对象的方式去实现sql语句,本文重点给大家介绍mybatis-plus条件构造器的操作代码,感兴趣的朋友一起看看吧
    2022-03-03
  • MybatisPlusInterceptor实现sql拦截器超详细教程

    MybatisPlusInterceptor实现sql拦截器超详细教程

    这篇文章主要给大家介绍了关于MybatisPlusInterceptor实现sql拦截器超详细教程的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-08-08
  • 详解Java多线程编程中LockSupport类的线程阻塞用法

    详解Java多线程编程中LockSupport类的线程阻塞用法

    LockSupport类提供了park()和unpark()两个方法来实现线程的阻塞和唤醒,下面我们就来详解Java多线程编程中LockSupport类的线程阻塞用法:
    2016-07-07
  • 详解Spring Data JPA系列之投影(Projection)的用法

    详解Spring Data JPA系列之投影(Projection)的用法

    本篇文章主要介绍了详解Spring Data JPA系列之投影(Projection)的用法,具有一定的参考价值,有兴趣的可以了解一下
    2017-07-07
  • Java虚拟机之对象创建过程与类加载机制及双亲委派模型

    Java虚拟机之对象创建过程与类加载机制及双亲委派模型

    这篇文章主要给大家介绍了关于Java虚拟机之对象创建过程与类加载机制及双亲委派模型的相关资料,本文通过示例代码以及图文介绍的非常详细,对大家学习或者使用java具有一定的参考学习价值,需要的朋友可以参考下
    2021-11-11
  • Java日常练习题,每天进步一点点(22)

    Java日常练习题,每天进步一点点(22)

    下面小编就为大家带来一篇Java基础的几道练习题(分享)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望可以帮到你
    2021-07-07
  • Java多线程并发之ReentrantLock

    Java多线程并发之ReentrantLock

    这篇文章主要介绍了Java 多线程并发ReentrantLock,文中有非常详细的代码示例,对正在学习java的小伙伴们有非常好的帮助,需要的朋友可以参考下
    2023-04-04

最新评论