Spring

Spring Boot Exit Codes – Create Custom Exit Code

Introduction:

When running a Spring Boot application, we get a system exit code of 0, when everything goes fine.  For any unhandled exceptions, the application returns with an exit code 1.

It’s possible for us to return a custom exit code from our Spring Boot application. In this tutorial, we’ll learn to do so.

Implementing ExitCodeGenerator:

Let’s start by creating a class that implements the ExitCodeGenerator interface:

We have overridden the getExitCode() method to return a value of 25. So, this application will now exit with an exit code of 25.

We have wrapped the SpringApplication.run() with the SpringApplication.exit() method.

As per the Spring documentation, we must call System.exit() with the result of the call to the SpringApplication.exit() method.

Listening to ExitCodeEvent:

We can register an event listener to listen to an ExitCodeEvent:

Spring Boot will fire this event when it finds an application-specific exit code. Now on an application exit, exitEvent() method will be invoked.

Working with ExitCodeExceptionMapper:

ExitCodeExceptionMapper is a strategy interface that we can use to provide mappings between exception types and exit codes.

Now, for an exception of type NumberFormatException, our application will exit with an exit code of 34 and so on.

Conclusion:

In this quick tutorial, we learned how to return a custom exit code in a Spring Boot application. We also implemented an event listener for the ExitCodeEvent.

Returning a correct exit code will help us while troubleshooting an application.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *