Search code examples
c#unity-interception

Using unity interception to solve exception handling as a crosscutting concern


I created my own behavior as follows:

public class BoundaryExceptionHandlingBehavior : IInterceptionBehavior
{


public IEnumerable<Type> GetRequiredInterfaces()
{
  return Type.EmptyTypes;
}

public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
  try
  {
    return getNext()(input, getNext);
  }
  catch (Exception ex)
  {
    return null; //this would be something else...
  }
}

public bool WillExecute
{
  get { return true; }
}

}

I have it setup correctly so that my behavior gets hit as expected. However, if any exception happens in whatever getNext() does, it doesn't hit my catch block. Can anyone clarify why? I'm not really looking to solve the problem as there's many ways to deal with exceptions, it's more that I don't understand what's going on, and I'd like to.


Solution

  • You can't catch any exception, if an Exception occurs it will be part of the Exception property of IMethodReturn.

    Like so:

    public IMethodReturn Invoke(IMethodInvocation input,
                    GetNextInterceptionBehaviorDelegate getNext)
    {
       IMethodReturn ret = getNext()(input, getNext);
       if(ret.Exception != null)
       {//the method you intercepted caused an exception
        //check if it is really a method
        if (input.MethodBase.MemberType == MemberTypes.Method)
        {
           MethodInfo method = (MethodInfo)input.MethodBase;
           if (method.ReturnType == typeof(void))
           {//you should only return null if the method you intercept returns void
              return null;
           }
           //if the method is supposed to return a value type (like int) 
           //returning null causes an exception
        }
       }
      return ret;
    }