How can I control exceptions on Spring Boot startup?

后端 未结 1 967
感动是毒
感动是毒 2021-01-19 19:41

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 st

1条回答
  •  抹茶落季
    2021-01-19 19:51

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

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

    0 讨论(0)
提交回复
热议问题