Spring Boot命令行运行器异常处理

10

我们正在使用Spring-boot来开发命令行应用。我们正在使用javax.validation来验证命令行参数。

现在,如果我们有一个验证错误,怎么打印友好的错误信息呢?我们不想显示堆栈跟踪。

当我们以CommandLineRunner形式运行Spring-boot时,是否有ExceptionHandler机制可供我们使用?

谢谢 Arun

    @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
@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);
    }
}

干净的执行

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

验证检查

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

验证错误

2014-12-25 20:51:13,325 ERROR [main] [o.s.b.SpringApplication.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]

完整的源代码

源代码可以在GitHub上找到。

2个回答

2
我遇到(几乎)相同的问题,但令我惊讶的是,从Spring Boot命令行程序中向用户显示错误的最清晰方法实际上是在CommandlineRunner.run()中记录任何错误消息后,使用System.exit(1)退出。Spring上下文将以清洁的方式关闭,但不会触发上下文启动失败事件,因此您不会得到所有其他干扰的日志输出。
您可能需要调整如何调用验证,以便您可以在run()内部自己捕获验证错误,并将其转换为日志+ System.exit()

0

不,没有内置的异常处理机制来处理CommandLineRunner引发的异常 - 请参阅org.springframework.boot.SpringApplication#runCommandLineRunners,将其包装在传统的Java异常处理块中会更容易。


不幸的是,在try catch块中包装run()语句并没有帮助。无论如何,感谢您的回复。 - Arun Avanathan
你能展示一下你如何使用javax.validation来验证你的参数吗?也许看一下这个会激发更多的想法。 - Biju Kunjummen
啊,我现在明白你的观点了。我认为这是可以接受的行为 - 从Spring的角度来看,如果启动属性未通过验证,则不要启动应用程序,而是在堆栈跟踪中显示确切的验证失败。然而,这并不特定于CommandLineRunners,无论有没有CommandLineRunners,它都应该具有相同的行为。 - Biju Kunjummen
2
如果验证失败,开发人员应该有选项来处理错误并显示优雅的错误消息。这类似于在Web服务中显示HTTP状态代码,例如BadRequest而不是堆栈跟踪。再次感谢。 - Arun Avanathan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接