I want to catch all exceptions/errors that occur in my application.
Therefor I searchd on stackoverflow and stubled over this question: Java Exception Listener
Now I am wondering if this can be accomplish in a better way.
My current application:
I am using the Spring framework with the Spring JPA in an standalone code without the web component. I have a Config.java
file with the four main Beans:
- Time Weaver
- Data Source
- entity Manager Factory
- transaction Manager
I now thought that I could maybe use something like the following:
package me.test;
import java.beans.ExceptionListener;
import org.springframework.stereotype.Component;
@Component
public class ErrorListener implements ExceptionListener {
@Override
public void exceptionThrown(Exception e) {
System.out.println("Some error occured ... That's bad :(");
}
}
I am not really sure if this ExceptionListener
works like I want him to work, so I thought maybe someone can explain to me if what I want is possible or not.
Maybe not with this Listener but with an other method?
Also a other general Question:
How do I register an Listener in general? Isn't there also a @EventListener
anotation? Do I have to put this before an method and then let it scan by spring as a part of a Component?
Or do I have to register it manually in my context?
Thanks :)
--- EDIT ---
The idea with the AfterThrowing
seems very nice (see comments below). Now my project is like the following:
in the Main:
new AnnotationConfigApplicationContext(Config.class);
Config.java
@EnableTransactionManagement
@ComponentScan("me.test.*")
@Configuration
@EnableJpaRepositories
@EnableAspectJAutoProxy
public class Config {
@AfterThrowing(pointcut = "execution(public * *(..)", throwing = "ex")
public void doRecoveryActions(DataAccessException ex) {
System.out.println("Error found");
}
/* loadTimeWeaver, dataSource, entityManagerFactory and transactionManager with the "@Bean" annotation */
}
And then in an random file something that throws an error like int i2 = 5 / 0;
and in an other class throw new Exception("test");
.
But unfortunately it is nor working :(
What am I doing wrong?
@Aspect public class AfterThrowingExample { @AfterThrowing( pointcut="execution(public * *(..)", throwing="ex") public void doRecoveryActions(DataAccessException ex) { // ... } }
– Nitin Prabhu Feb 14 '16 at 00:38