Reputation: 446
Problem: I'm using Spring Boot 1.4.3 (spring-boot-starter-web) and running a method when it boots that might throw an exception. Currently if exception is thrown, Spring shuts down Tomcat and exits. How can I make this exception NON-fatal? In other words, I still want web server to continue running.
Here's my code:
@EventListener
public void runOnStartup(ApplicationReadyEvent event) {
do_stuff_that_might_runtime_exception();
}
But if my custom RuntimeException is thrown I see:
..[info] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@77d67cf3: startup date [Thu Jan 12 13:23:03 CST 2017]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@2df3b89c
..[info] o.s.c.support.DefaultLifecycleProcessor : Stopping beans in phase 0
..[info] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
..[info] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans
..[info] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@7b6860f9: startup date [Thu Jan 12 13:23:06 CST 2017]; parent: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@77d67cf3
..[info] o.apache.catalina.core.StandardService : Stopping service Tomcat
Upvotes: 2
Views: 3443
Reputation: 2421
Exceptions Get propagated to the caller , or the previous stack only if they are unhandled, and Bubble up the stack in similar fashion, Ultimately leading to run method of the thread or main method in case it is on the main thread.
To break the chain of propagation handle the exception in between gracefully on one of the stack. In Current case the ideal place would be to wrap the code in guard block .
@EventListener
public void runOnStartup(ApplicationReadyEvent event) {
try {
do_stuff_that_might_runtime_exception();
} catch(RuntimeException runtimeException){
// Handle Exception Here
runtimeException.printStackTrace();
}
}
Also , Always ensure that you decide on the Scenarios you want to take care of , and try to avoid generic exception catches, they might lead to unnecessary logical coverups. For example if you expect the guarded block to throw FileNotFoundException , try to catch only FileNotFoundException , rather RuntimeException or Exception or worst Throwable. But Implementation detail is developer choice and need basis.
Upvotes: 1
Reputation: 5045
It looks like it is your code that may throw he exception, therefore it is also your code which must catch the exception so it doesn't unwind the callstack.
@EventListener
public void runOnStartup (ApplicationReadyEvent event){
try {
do_stuff_that_might_runtime_exception();
} catch (Exception e) {
log.error("something occurred", e);
}
}
Upvotes: 0