Reputation: 23
short Summary : I want to create a wrapper/Interceptor for our java clients making external call and we have a lot of different java clients so I don't want to map exception one by one.
public Object handleRequest(Object delegate, Method method, Object[] objects) {
Object result = null;
try {
result = method.invoke(delegate, objects);
// do some logic
} catch ( IllegalAccessException | IllegalArgumentException e) {
// do nothing
} catch (InvocationTargetException e) {
throw e.getCause(); //java: unreported exception java.lang.Throwable; must be caught or declared to be thrown
}
return result;
};
};
}
In the code above, what I would like to do is throw the exception that the delegate is throwing (which would be obtainable by getting e.getCause(), but it is throwable). Since we have many maaany clients, I want to avoid checking it with many if and else statements and checking with isInstanceOf() (or other variations of it). Is there a way for me to throw the whatever e.getCause() as type of that specific type programatically?
Upvotes: 0
Views: 219
Reputation: 198033
No. If you are handed an arbitrary Method
, you can't make the caller know what particular type of exception that method throws. You can of course throw Throwable
and just throw e.getCause()
, but it sounds like that's what you don't want to do -- but there's no way around it given the rest of your design.
You could move away from reflection and use interfaces and method references, but it's not clear from the context how feasible that is.
Upvotes: 1