【问题标题】:How can I control exceptions on Spring Boot startup?如何控制 Spring Boot 启动时的异常?
【发布时间】:2018-11-10 15:31:33
【问题描述】:

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

证书文件正在@Component 类中的@PostConstruct 方法中加载。如果它抛出 FileNotFoundException,我会捕获它并抛出我创建的特定异常。在任何情况下我都需要抛出异常,因为如果该文件未被读取,我不希望应用程序加载。

我试过这个:

@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方法内部抛出。

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

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    您可以抓住BeanCreationException 并打开它以获取原始原因。您可以使用以下代码片段

    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 中并抛出。

    【讨论】:

    • 谢谢。这确实让我知道抛出了什么异常并对其进行处理。不幸的是,它在显示整个堆栈跟踪之后才这样做。这不能预防吗?
    猜你喜欢
    • 2019-12-01
    • 2017-10-21
    • 2019-02-18
    • 2021-04-13
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    相关资源
    最近更新 更多