Search code examples
javaspring

Is there a way to catch @Service initialization errors in Spring Boot


I am currently using Spring Boot with Java 8 using the following snippit in my pom.xml:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.18</version>
    <relativePath/> 
</parent>

I have a Java Spring @Service, whose initailization can throw an exception:

@Service 
public class FallibleService {
    public FallibleService() throws SomeException {
        /*
            Does something fallible, like opening a file, etc.
        */
        randomOperation();
    }
}

Is there a way to register an error handler for the construction of this object? Specifically, I want the application to close, with a specific error message provided to the user, rather than just spewing an unreadable stacktrace.

I attempted to inline the error management using a try catch block as shown below:

@Service 
public class FallibleService {
    public FallibleService() {
        try {
            randomOperation();
        } catch (SomeException e) {
            logger.error("Exception occurred!", e);
            System.exit(0);
        }
    }
}

However, System.exit(0) on my current version of spring. There are ways to fix this, however this doesn't seem idiomatic.


Solution

  • You can handle stuff like this with an ApplicationListener

    @Component
    @Slf4j
    public class FailedListener implements ApplicationListener<ApplicationFailedEvent> {
        
        @Override
        public void onApplicationEvent(ApplicationFailedEvent event) {
            log.error(event.getException().getLocalizedMessage());
            // put whatever you want in here
            System.exit(0);
        }
    }