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:

@SpringBootApplication
public class SampleApplication implements ExitCodeGenerator {
 
    public static void main(String[] args) {
        System.exit(SpringApplication
          .exit(SpringApplication.run(SampleApplication.class, args)));
    }
  
    @Override
    public int getExitCode() {
        return 25;
    }
}

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:

@Bean
SampleEventListener sampleEventListener() {
    return new SampleEventListener();
}
 
private static class SampleEventListener {

    @EventListener
    public void exitEvent(ExitCodeEvent event) {
        LOG.info("Application Exit code: {}", event.getExitCode());
    }
}

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.

@Bean
ExitCodeExceptionMapper exitCodeToexceptionMapper() {
    return exception -> {
        
        if (exception.getCause() instanceof NumberFormatException) {
            return 34;
        }
        if (exception.getCause() instanceof CustomTypeException) {
            return 45;
        }
        ...
        return 1;
    };
}

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.

One comment

Hi Shubhra,

I have used the same pattern ExitCodeExceptionMapper Bean in my main class. That is catching all exception from my app(that is how i coded). But I want to know how to test this. Since I’m having it in my main class. Actually stuck at writing unit tests. Do you have any idea/ reference code?

Leave a Comment

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