5

私は次のように独自の動作を作成しました。

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

}

動作が期待どおりにヒットするように、正しく設定されています。ただし、getNext()で例外が発生しても、catchブロックにはヒットしません。誰かが理由を明確にできますか?例外に対処する方法はたくさんあるので、私は実際には問題を解決しようとは思っていません。何が起こっているのかわからないというだけでなく、やりたいと思っています。

4

3 に答える 3

8

例外をキャッチすることはできません。例外が発生した場合、それはIMethodReturnのExceptionプロパティの一部になります。

そのようです:

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;
}
于 2012-04-05T09:37:07.047 に答える