0

I would like to intercept exception throw and log it using bytebuddy. Is it possible? If not what are the other tools that would allow me to do that?

user3364192
  • 3,783
  • 2
  • 21
  • 30
  • 1
    If you do this in code you don't understand it is likely to log spurious exceptions. You are better of trying to fix the code using your debugger where you can trap specific Exceptions or all exception thrown. – Peter Lawrey Mar 30 '16 at 22:38

1 Answers1

2

You can write a Java agent using an AgentBuilder where you intercept classes using a simple MethodDelegation on all relevant types:

class MyInterceptor {
  @RuntimeType
  public static Object intercept(@SuperClass Callable<?> zuper) throws Exception {
    try {
      return zuper.call();
    } catch (Throwable t) {
      // log here
      throw t;
    }
  }
}

For a tutorial on how to implement an agent, you can read this article.

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
  • Could you please advice what would it take have `MethodDelegation.toField` wrapped into try-catch block? What's cool about `MethodDelegation.toField` is that it alters generated code to number of arguments of intercepted method. I couldn't find exact location in bytebuddy where it happens. Could you please point me ? – expert Dec 11 '22 at 16:35
  • 1
    There's no mechanism for that, you'd delegate to a method doing that. – Rafael Winterhalter Dec 12 '22 at 19:03