使用统一拦截来解决异常处理作为横切关注点

gre*_*007 5 c# unity-interception

我创建了自己的行为,如下所示:

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; }
}

}
Run Code Online (Sandbox Code Playgroud)

我已正确设置它,以便我的行为按预期命中.但是,如果在任何getNext()中发生任何异常,它都不会触及我的catch块.谁能澄清为什么?我并不是真的想要解决问题,因为有许多方法可以处理异常,更多的是我不明白发生了什么,我想.

gid*_*eon 7

您无法捕获任何异常,如果发生异常,它将成为IMethodReturnException属性的一部分.

像这样:

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;
}
Run Code Online (Sandbox Code Playgroud)