如何在Spring Boot启动时控制异常? [英] How can I control exceptions on Spring Boot startup?

查看:237
本文介绍了如何在Spring Boot启动时控制异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Spring Boot应用程序尝试在启动时加载一些证书文件.我希望能够在无法加载该文件而不是巨大的堆栈跟踪时显示一条明智的消息.

My Spring Boot application tries to load some certificate files on startup. I want to be able to show a sensible message when that file cannot be loaded instead of a huge stack trace.

证书文件正在@Component类内的@PostConstruct方法中加载.如果它抛出FileNotFoundException,则将其捕获并抛出我创建的特定异常.无论如何,我都需要抛出异常,因为如果不读取该文件,我不希望应用程序加载.

The certificate file is being loaded in a @PostConstruct method inside a @Component class. If it throws a FileNotFoundException I catch it and throw a specific exception that I created. I need to throw an exception in any case because I don't want the application to load if that file is not read.

我尝试过:

@SpringBootApplication
public class FileLoadTestApplication {
    public static void main(String[] args) {
        try {
            SpringApplication.run(FileLoadTestApplication .class, args);
        } catch (Exception e) {
            LOGGER.error("Application ending due to an error.");
            if (e.getClass().equals(ConfigException.class)) {
                if (e.getCause().getClass().equals(FileNotFoundException.class)) {
                    LOGGER.error("Unable to read file: " + e.getCause().getMessage());
                } else {
                    LOGGER.error("Initial configuration failed.", e.getCause());
                }
            }
        }
    }
}

但不会在run方法内部抛出异常.

but the exception is not thrown inside inside the run method.

如何控制启动时的一些异常,以便在关闭前显示提示信息?

How can I control some exceptions on startup so that I show an informative message before closing?

推荐答案

您可以捕获BeanCreationException并将其展开以获得原始原因.您可以使用以下代码片段

You can catch the BeanCreationException and unwrap it to get the original cause. You can use the following code fragment

public static void main(String[] args) {
    try {
        SpringApplication.run(FileLoadTestApplication.class, args);
    } catch (BeanCreationException ex) {
        Throwable realCause = unwrap(ex);
        // Perform action based on real cause
    }
}

public static Throwable unwrap(Throwable ex) {
    if (ex != null && BeanCreationException.class.isAssignableFrom(ex.getClass())) {
        return unwrap(ex.getCause());
    } else {
        return ex;
    }
}

当带有@PostConstruct注释的方法抛出异常时,Spring会将其包装在BeanCreationException中并抛出.

When the @PostConstruct annotated method throws an exception, Spring wraps it inside the BeanCreationException and throws back.

这篇关于如何在Spring Boot启动时控制异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆