How to inject a logging statement before every catch block in java

719 views Asked by At

I initially started with Aspect Oriented Programming using JBoss , and have implemented their code injection for - Before and After the method gets called and After the Method Throws an Exception. Now i want to know how do we inject code within the method ? I want to inject a Logging statement before every catch block gets executed , How do we do that using java ?

1

There are 1 answers

5
kriegaex On

I do not know much about JBoss AOP, but in any case you can use AspectJ because it features a handler() pointcut.

Driver application:

package de.scrum_master.app;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeoutException;

import javax.naming.NamingException;

public class Application {
    public static void throwRandomException() throws TimeoutException, IOException, NamingException {
        switch (new Random().nextInt(5)) {
            case 0: throw new TimeoutException("too late, baby");
            case 1: throw new FileNotFoundException("file.txt");
            case 2: throw new IOException("no read permission");
            case 3: throw new NullPointerException("cannot call method on non-existent object");
            case 4: throw new NamingException("unknown name");
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            try { throwRandomException(); }
            catch (NullPointerException e) {}
            catch (FileNotFoundException e) {}
            catch (TimeoutException e) {}
            catch (IOException e) {}
            catch (NamingException e) {}
        }
    }
}

Aspect:

package de.scrum_master.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class CaughtExceptionLogger {
    @Before("handler(*) && args(e)")
    public void logCaughtException(JoinPoint thisJoinPoint, Exception e) {
        System.out.println(thisJoinPoint + " -> " + e.getMessage());
    }
}

Console output:

handler(catch(TimeoutException)) -> too late, baby
handler(catch(FileNotFoundException)) -> file.txt
handler(catch(NamingException)) -> unknown name
handler(catch(TimeoutException)) -> too late, baby
handler(catch(NamingException)) -> unknown name
handler(catch(NamingException)) -> unknown name
handler(catch(NullPointerException)) -> cannot call method on non-existent object
handler(catch(FileNotFoundException)) -> file.txt
handler(catch(FileNotFoundException)) -> file.txt
handler(catch(NullPointerException)) -> cannot call method on non-existent object