Custom Failure Analyzer For Spring Boot Applications

Arvind Kumar
2 min readFeb 29, 2020

Spring boot framework is very popular among microservices developers. We all are aware of the existing error messages or failure report that gets generated when there is any error/issue in starting the spring boot application. These errors can be one of the followings —

NoSuchMethodError
PortInUseFailureAnalyzer
ValidationExceptionFailureAnalyzer

And many more…

If you have sample spring boot application then All of these can be found under below package —

org.springframework.boot.diagnostics.analyzer

Below is the snapshot for the same…

So far, it’s all about the existing failure analyzer that comes with Spring Boot Framework.

What, If I want to create my own failure analyzer?

Here is the solution for that-

Create your own class and extend it with the interface FailureAnalyzer like below —

public class MyFailureAnalyzer implements FailureAnalyzer {
@Override
public FailureAnalysis analyze(Throwable failure) {
return new FailureAnalysis("My custom message", failure.getMessage(), failure);
}
}

Now, we have our custom analyzer ready.

I have to register it somewhere so that it gets picked up by spring boot when spring boot application is starting. I have to create a file spring.factories under resources/META-INF like below —

Its content is like below —

org.springframework.boot.diagnostics.FailureAnalyzer=\
com.gl.failureanalyzerdemo.MyFailureAnalyzer,\
com.gl.failureanalyzerdemo.MyFailureAnalyzer2

Here, I have registered two failure analyzers.

That’s all we have to do now run the application, if there is an error while starting the application it will be picked up by this failure Analyzer and the report will be generated as per the definition in the custom failure analyzer. Below is the screenshot of the console log that has printed the custom message —

For more information on spring boot, microservices and latest trends in the software development industry follow me on youtube @GreenLeanrer

All the source code can be found on GitHub @GreenLearner

Cheers!!

Happy Coding!!

--

--