Indraneel Bende
Indraneel Bende

Reputation: 3486

Spring Boot- Throw an Error and Stop application starting up on some criteria

I am working on an application where in a bean's post construct method i am adding some logic to create an object. Now , what I want to do is, if there is an exception and the creation of the object has some error, then do not let the application start up. Yes, I can see an exception being thrown on the console when it starts up, if there is any issue with the construction of an object, but I would like something better than that to inform me that construction of an object has failed, and what better criteria than application failing to start up.

Any help is much appreciated.

Thank you in advance.

Upvotes: 4

Views: 4741

Answers (1)

sanit
sanit

Reputation: 1764

You can look for FailureAnalyzer for this type of requirements where additional information will given in case application start failes. If any exception raised during application start, all the FailureAnalyzer classes will be invoked in a sequence. If any of the FailureAnalyzer class returning FailureAnalysis object then the exception won't be propagated to further FailureAnalysis classes.

Please make sure you register your FailureAnalysis class in resource/META-INF/spring.factories file.

@Component
public class SomeObject {

  @PostConstruct
  public void init() throws Exception {
    throw new Exception("SomeObject init threw exception");
  }
}

public class ObjConstructionFailureAnalyzer extends 
                     AbstractFailureAnalyzer<BeanCreationException> {

  @Override
  protected FailureAnalysis analyze(Throwable rootFailure, 
                        BeanCreationException cause) {
    System.out.println("\n===>ObjConstructionFailureAnalyzer::analyze()\n");
    String desciption = "Object creation failed, [Reason]: " + 
                                                     cause.getMessage();
    String action = "Please handle exceptions in your init methods";
    return new FailureAnalysis(desciption, action, cause);
  }
}

In spring.factories file

org.springframework.boot.diagnostics.FailureAnalyzer=examples.stackoverflow.ObjConstructionFailureAnalyzer

Exception stacktrace

===>ObjConstructionFailureAnalyzer::analyze()

2018-02-21 10:16:59.552 ERROR 9500 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :

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


Description:

Object creation failed, [Reason]: Error creating bean with name 'someObject': Invocation of init method failed; nested exception is java.lang.Exception: SomeObject init threw exception

Action:

Please handle exceptions in your init methods

Project Structure

You can additionally visit here for code sample.

Upvotes: 3

Related Questions