Spring loading CommandLineRunner exception handling

We use Spring-boot for a command line application. We use javax.validation to check command line arguments.

Now, if we have a validation error, how can we print a friendly error message? We do not want to show the stack trace.

Is there an ExceptionHandler mechanism that we could use when we run Spring-boot as CommandLineRunner?

Thanks Arun

A source

@SpringBootApplication public class Deploy implements CommandLineRunner { private static final Logger LOGGER = LoggerFactory.getLogger(Deploy.class); @Autowired private DeployConfig config; @Autowired private DeployService deployService; /** * mvn clean package spring-boot:repackage * java -jar target/spring-boot-example-1.0.0-SNAPSHOT.jar --spring.profiles.active=qa --version=1.0 * * @param strings arguments * @throws Exception */ @Override public void run(String... strings) throws Exception { try { deployService.deploy(config); } catch (Exception ve) { LOGGER.error("Error : {}", ve.getMessage()); } LOGGER.info("Created stack={}", config.getVersion()); } public static void main(String... args) { LOGGER.info("Starting to run..."); SpringApplication.run(Deploy.class, args); LOGGER.info("Completed the run..."); } } 

Configuration

 @Configuration @EnableConfigurationProperties @ConfigurationProperties public class DeployConfig { @NotNull private String hello; @NotNull private String version; private String envKey; public String getHello() { return hello; } public void setHello(String hello) { this.hello = hello; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getEnvKey() { return envKey; } public void setEnvKey(String envKey) { this.envKey = envKey; } public String toString() { return ToStringBuilder.reflectionToString(this); } } 

Clean run

 mvn clean package spring-boot:repackage java -jar target/spring-boot-example-1.0.0-SNAPSHOT.jar --spring.profiles.active=preprod,qa --version=1.0 

Verification check

 java -jar target/spring-boot-example-1.0.0-SNAPSHOT.jar --spring.profiles.active=preprod,qa 

Verification Error

 2014-12-25 20:51:13,325 ERROR [main] [osbSpringApplication.run()] - Application startup failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'deploy': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.example.DeployConfig com.example.Deploy.config; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'deployConfig': Could not bind properties; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'target' on field 'version': rejected value [null]; codes [NotNull.target.version,NotNull.version,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [target.version,version]; arguments []; default message [version]]; default message [may not be null] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.1.3.RELEASE.jar!/:4.1.3.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202) ~[spring-beans-4.1.3.RELEASE.jar!/:4.1.3.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) ~[spring-beans-4.1.3.RELEASE.jar!/:4.1.3.RELEASE] 

Full source code

Source can be found on github

+6
source share
2 answers

I ran into (almost) the same problem and (to my great surprise), it seems the cleanest way to show the user error from the Spring boot command line program is actually System.exit(1) from CommandlineRunner.run() , after registering any message about the error you want. The Spring context will be closed anyway, but it does not raise a failure event when the context starts, so you won’t get all the other distracting log output.

You may need to set up a method for triggering validation so that you yourself can catch validation errors inside run() and translate them into the + System.exit() log.

+2
source

No, there are no built-in exception handling mechanisms for handling exception from CommandLineRunner - see org.springframework.boot.SpringApplication#runCommandLineRunners , it will be easier to just wrap it around your traditional Java exception handling blocks

0
source

Source: https://habr.com/ru/post/980142/


All Articles