How to avoid repeating complex exception handling code in a wrapper class?

I have this class that wraps an object:

public class MyWrapper implements MyInterface {

    private MyInterface wrappedObj;

    public MyWrapper(MyInterface obj) {
        this.wrappedObj = obj;
    }

    @Override
    public String ping(String s) {
        return wrappedObj.ping(s);
    }

    @Override
    public String doSomething(int i, String s) {
        return wrappedObj.doSomething(i, s);
    }

// many more methods ...
}

Now I want to add complex exception handling around the wrappedObj call.

The same goes for all methods.

How to avoid repeating the same exception handling code over and over?

+4
source share
2 answers

If your exception handling is completely general, you can implement a shell like InvocationHandler:

public class ExceptionHandler implements java.lang.reflect.InvocationHandler {
    public ExceptionHandler(Object impl) {
        impl_ = impl;
    }

    @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            return method.invoke(impl_, args);
        }
        catch (Exception e) {
            // do exception handling magic and return something useful
            return ...;
        }
    }

    private Object impl_;
}

and then wrap it around the instance as follows:

MyInterface instance = ...
MyInterface wrapper = (MyInterface)java.lang.reflect.Proxy.newProxyInstance(
   instance.getClass().getClassLoader(), 
   new Class[] { MyInterface.class }, 
   new ExceptionHandler(instance));

wrapper.ping("hello");
0
source

If you want to avoid the cost of reflection than just use the router function.

@Override
public String ping(String s) {
    return (String) call("ping");
}

private Object call(String func) {
    try {
      switch(func) {
        case "ping": return wrappedObj.ping(s);
        // ... rest of functions ... //
      }
    } catch(Exception e) {
      log(e);
    }
}

, . ( , , )

...

Java Runtime Thread.setDefaultUncaughtExceptionHandler
ThreadGroup ThreadGroup.uncaughtException
Thread.setUncaughtExceptionHandler

, , .

0

Source: https://habr.com/ru/post/1677376/


All Articles