V
V
Victor Potapov2015-06-02 09:49:19
Java
Victor Potapov, 2015-06-02 09:49:19

How to catch all uncatched exceptions with aspectj?

After searching for information, I came across a similar design

@AfterThrowing(pointcut = "execution(* com.mycompany.package..* (..))", throwing = "ex")

But the problem is that such a pointcut catches ALL exceptions. Regardless of whether we processed them or not. Is it possible to force aspectj to catch unhandled exceptions?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sasah, 2015-06-08
@midikko

Toster.java

package com.toster.dao;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Toster {
}

TosterAspect.java
package com.toster.dao;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Aspect
public class TosterAspect {

    private static final Logger LOG = LoggerFactory.getLogger(TosterAspect.class);

    @Around("execution(* *(..)) && @annotation(tr)")
    public Object request(final ProceedingJoinPoint pjp, final Toster tr) throws Throwable {
        try {
            LOG.info("Invoke {}", pjp.toShortString());
            final Object proceed = pjp.proceed();
            LOG.info("Return {}", proceed);
            return proceed;
        } catch (Exception e) {
            LOG.error("Error", e);
            throw e; //TODO
        }
    }

}

AspectConfiguration.java
package com.toster.dao;

import org.aspectj.lang.Aspects;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@EnableAspectJAutoProxy
public class AspectConfiguration {

    @Bean
    public TosterAspect tosterAspect() {
        return Aspects.aspectOf(TosterAspect.class);
    }

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question