Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot console app global exception handling using Thread.setDefaultUncaughtExceptionHandler is not being invoked

I have a spring boot console app (i.e. not MVC or REST) and I need to setup a global exception handling. @ControlerAdvice/@Messagehandler are obviously not and option so I'm trying to use Thread.setDefaultUncaughtExceptionHandler instead. Observation is that after throwing an exception, the Thread.setDefaultUncaughtExceptionHandlerhandler is not being invoked. I'm looking for advice as to why this is not working or recommendation on using a different stratgy

@IntegrationComponentScan
@EnableIntegration
public class BatchLoaderCliApplication  {
    @PostConstruct
    public void init() {
        Thread.setDefaultUncaughtExceptionHandler((t,e)->System.out.println("in exception handler"));

    }

    @Bean
    public ApplicationRunner runner() {
        return args -> {
                   System.out.println(1/0)
                };
        }

java.lang.IllegalStateException: Failed to execute ApplicationRunner at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:773) at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:760) at org.springframework.boot.SpringApplication.run(SpringApplication.java:318) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1213) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1202) at com.somecom.batchloader.BatchLoaderCliApplication.main(BatchLoaderCliApplication.java:54) Caused by: java.lang.ArithmeticException: / by zero at com.somecom.batchloader.BatchLoaderCliApplication.lambda$1(BatchLoaderCliApplication.java:117) at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:770) ... 5 more

like image 713
Kash22 Avatar asked Jun 15 '26 20:06

Kash22


1 Answers

Spring Boot has a default mechanism using registered SpringBootExceptionReporter implementations. By default there is one delegating to FailureAnalyzer implementations and finally passing results to FailureAnalysisReporter.

For custom handling you can either

  • register your custom SpringBootExceptionReporter to extend/override default behaviour
  • register custom FailureAnalyzer to handle specific exceptions
  • register a custom FailureAnalysisReporter to handle all failures different

Registration is done by adding a local file META-INF/spring.factories which contains a (properties format) line with the full spring interface name as key and all your implementations as value (comma separated).

like image 137
Arne Burmeister Avatar answered Jun 17 '26 09:06

Arne Burmeister