jboss - How to inject a logging statement before every catch block in java -
i started aspect oriented programming using jboss , , have implemented code injection - before , after method gets called , after method throws exception. want know how inject code within method ? want inject logging statement before every catch block gets executed , how using java ?
i not know jboss aop, in case can use aspectj because features 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) { (int = 0; < 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)) -> late, baby handler(catch(filenotfoundexception)) -> file.txt handler(catch(namingexception)) -> unknown name handler(catch(timeoutexception)) -> 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
Comments
Post a Comment