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:

@SpringBootApplication
public class SpringBootExitCodeApplication implements ExitCodeGenerator {

	public static void main(String[] args) {
		System.exit(SpringApplication
				.exit(SpringApplication.run(SpringBootExitCodeApplication.class, args)));
	}

	@Override
	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 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.

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.

	@Bean
	ExitCodeExceptionMapper exitCodeToexceptionMapper() {
		return exception -> {

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

	@Bean
	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

	@Bean
	SampleEventListener sampleEventListener() {
		return new SampleEventListener();
	}

	private static class SampleEventListener {

		@EventListener
		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.