java Spring boot CommandLineRunner 异常处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27644890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:10:24  来源:igfitidea点击:

Spring boot CommandLineRunner Exception Handling

javaspringvalidationspring-boot

提问by Arun Avanathan

We are using Spring-boot for a commandline application. We are using javax.validation for validating command-line arguments.

我们将 Spring-boot 用于命令行应用程序。我们使用 javax.validation 来验证命令行参数。

Now, if we have a validation error how can we print friendly error message? We don't want to show Stack trace.

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

Is there a ExceptionHandler mechanism we could use when we are running Spring-boot as CommandLineRunner?

当我们将 Spring-boot 作为 CommandLineRunner 运行时,是否有我们可以使用的 ExceptionHandler 机制?

Thanks Arun

谢谢阿伦

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

Validation Check

验证检查

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

Validation Error

验证错误

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]

Complete Source

完整来源

Source can be found in GitHub

源代码可以在GitHub找到

回答by Karsten

I've run into (almost) the same problem, and (much to my surprise) it seems the cleanest way to display an error to the user from a Spring Boot command line program is to actually System.exit(1)from CommandlineRunner.run(), after logging whatever error message you want. The Spring context will shut down cleanly anyway, but it doesn't trigger the context startup failure events, so you don't get all the other distracting log output.

我遇到了(几乎)同样的问题,并且(令我惊讶的是)从 Spring Boot 命令行程序向用户显示错误的最干净的方法似乎是在记录任何你想要的错误消息后实际上是System.exit(1)from CommandlineRunner.run(). Spring 上下文无论如何都会干净利落地关闭,但它不会触发上下文启动失败事件,因此您不会获得所有其他分散注意力的日志输出。

You might have to adjust how you call the validation so you can catch the validation errors yourself inside run()and translate them into log + System.exit().

您可能需要调整调用验证的方式,以便您可以自己在内部捕获验证错误run()并将它们转换为 log + System.exit()

回答by Biju Kunjummen

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

不,没有内置的异常处理机制来处理来自CommandLineRunners-see 的异常org.springframework.boot.SpringApplication#runCommandLineRunners,将它包裹在传统的 java 异常处理块周围会更容易