Unity Interception and Exceptions
-
06-07-2019 - |
Question
i´m currently dealing with an issue where i have a lot of iterfaces and their implementations all created with unity. those classes contain some methods that throw exceptions on a regular base and i wanted to create a dynamic proxy around those classes so i can catch all exceptions occured in methods do handle them somewhere else.
As i´m playing with Unity, i wonder if something like this can be done using Unity Interception.
i.e. create a TransparentProxyInterceptor and wrap a try-catch block around the invocatino of these methods. is this possible at all or am i going into the wrong direction? thanks
Solution
Yes, Unity interception (AOP) is an excellent way to deal with exception handling. You can add all kinds of behavior like:
- write to a log file or the event log
- send an email
- increment a performance counter
- auto retry on timeout or lock exception
- rethrow a different error
Your call handler will look something like:
public override IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
IMethodReturn result = getNext()(input, getNext);
if (result.Exception != null)
{
// do something
}
return result;
}