I have a Spring Boot application implemented CommandLineRunner. I wanted to return -1 as exit code if there is any error/exception happens and return 0 if no exception.
public class MyApplication implements CommandLineRunner{
private static Logger logger = LoggerFactory.getLogger(MyApplication.class);
@Override
public void run(String... args) throws Exception {
// to do stuff. exception may happen here.
}
public static void main(String[] args) {
try{
readSetting(args);
SpringApplication.run(MyApplication.class, args).close();
}catch(Exception e){
logger.error("######## main ########");
java.util.Date end_time = new java.util.Date();
logger.error(e.getMessage(), e);
logger.error(SystemConfig.AppName + " System issue end at " + end_time);
System.exit(-1);
}
System.exit(0);
}
...
}
I have tried System.exit(), SpringApplication.exit(MyApplication.context, exitCodeGenerator), etc. But it still return 0 when I throw an exception!
I have tried solutions from here:
https://sdqali.in/blog/2016/04/17/programmable-exit-codes-for-spring-command-line-applications/
Please help!
There is a nice article answering your question on https://www.baeldung.com/spring-boot-exit-codes. Here is the gist:
@SpringBootApplication
public class CLI implements CommandLineRunner, ExitCodeGenerator {
private int exitCode; // initialized with 0
public static void main(String... args) {
System.exit(SpringApplication.exit(SpringApplication.run(CLI.class, args)));
}
/**
* This is overridden from CommandLineRunner
*/
@Override
public void run(String... args) {
// Do what you have to do, but don't call System.exit in your code
this.exitCode = 1;
}
/**
* This is overridden from ExitCodeGenerator
*/
@Override
public int getExitCode() {
return this.exitCode;
}
}