Managing Spring Boot Exit Code

Spread the love

1. Overview

Every application returns exit code on exit; this code can be any integer value including negative values.

In this quick tutorial, we’re going to find out how we can return exit codes from a Spring Boot application.

2. Spring Boot and Exit Codes

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.

3. Implementation

Spring Boot provides three methods that allow us to work with exit codes.

3.1. ExitCodeGenerator 

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

public class SpringBootExitCodeApplication implements ExitCodeGenerator {

	public static void main(String[] args) {
				.exit(, args)));

	public int getExitCode() {
		return 33;

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

We have wrapped the 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.

Error Code for System Exit

3.2. ExitCodeExceptionMapper

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

	ExitCodeExceptionMapper exitCodeToexceptionMapper() {
		return exception -> {

			if (exception.getCause() instanceof NumberFormatException) {
				return 34;
			if (exception.getCause() instanceof NullPointerException) {
				return 45;
			return 1;

	CommandLineRunner createException() {
		return args -> Integer.parseInt("test") ;

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

Spring Exiot Code 34

3.3. ExitCodeEvent

Next, we’ll capture an ExitCodeEvent to read the exit code of our applicationFor this, we simply register an event listener which subscribes to ExitCodeEvents

	SampleEventListener sampleEventListener() {
		return new SampleEventListener();

	private static class SampleEventListener {

		public void exitEvent(ExitCodeEvent event) {
			System.out.println("Application Exit code: " + event.getExitCode());

Now, when the application exits, the method exitEvent() will be invoked and we can read the exit code from the event.

4. Conclusion

In this article, we’ve gone through multiple options provided by Spring Boot to work with exit codes.

It’s very important for any application to return the right error code while exiting. The exit code determines the state of the application when the exit happened. In addition to that, it helps in troubleshooting.