Reputation: 76547
I want to use AspectJ to catch a NoResultException
and return null instead.
(Obviously I'm an Aspect noob)
Here's the method that does the querying:
@Override
public Company getCompanyBySomeNumber(String someNumber) {
TypedQuery<Company> query = em.createQuery("select c from Company c where c.someNo = ?1", Company.class);
query.setParameter(1, someNumber);
return query.getSingleResult();
I have several hundred of these calls and I don't want to litter each and every one with a try/catch
to change the NoResultException
into a null result.
So I want to write an aspect to catch the exception and change the result to null
.
Here's the aspect code (please note I'm using annotations). Something like this:
@Aspect
public class NullifyNoResultException {
@Pointcut("execution(my.namespace.where.the.queries.are * *Throwable(..))")
void throwableMethod() {}
@Around("throwableMethod()")
public void swallowThrowing(ProceedingJoinPoint pjp) {
try {
pjp.proceed();
} catch (NoResultException nre) {
//TODO change the return value to null
How do I change the return value to null
Upvotes: 0
Views: 479
Reputation: 6810
Have you tried to change your method to:
@Around("throwableMethod()")
public Object swallowThrowing(ProceedingJoinPoint pjp) {
try {
return pjp.proceed();
} catch (NoResultException nre) {
return null;
}
}
Upvotes: 1