2011-11-07 43 views
3

我有一個像IInterceptionBehavior打擊:如何通過IInterceptionBehavior吞下例外?

public class TraceBehavior : IInterceptionBehavior 
{ 
    public IEnumerable<Type> GetRequiredInterfaces() 
    { 
     return Type.EmptyTypes; 
    } 

    public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) 
    { 
     Console.WriteLine(string.Format("Invoke method:{0}",input.MethodBase.ToString())); 
     IMethodReturn result = getNext()(input, getNext); 
     if (result.Exception == null) 
     { 
      Console.WriteLine("Invoke successful!"); 
     } 
     else 
     { 
      Console.WriteLine(string.Format("Invoke faild, error: {0}", result.Exception.Message)); 
      result.Exception = null; 
     } 
     return result; 
    } 

    public bool WillExecute { get { return true; } } 
} 

不管我是否把它在方法還是不行,例外總是拋出。任何人都可以幫助我?

回答

3

代碼看起來不錯,但你有沒有看到如何攔截註冊和對象是如何被調用。

假設正在調用攔截,那麼如果我猜測它將調用的方法返回值類型,並且IMethodReturn.ReturnValue爲空,這將導致NullReferenceException

如果是這樣的話,那麼也許返回一個值類型的默認值會解決您的問題:

public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) 
{ 
    Console.WriteLine(string.Format("Invoke method:{0}", input.MethodBase.ToString())); 
    IMethodReturn result = getNext()(input, getNext); 
    if (result.Exception == null) 
    { 
     Console.WriteLine("Invoke successful!"); 
    } 
    else 
    { 
     Console.WriteLine(string.Format("Invoke faild, error: {0}", result.Exception.Message)); 
     result.Exception = null; 

     Type type = ((MethodInfo)input.MethodBase).ReturnType; 

     if (type.IsValueType) 
     { 
      result.ReturnValue = Activator.CreateInstance(type); 
     } 
    } 
    return result; 
} 
+0

喜,GETNEXT()得到處理,並通過Invoke方法調用。作爲getNext()。調用(input,getNext)。我想知道在調用的方法中發生了什麼,假設它,目標方法拋出異常並將其攜帶到result.Exception中?我怎樣才能定義「編譯時間」方面? –