2011-06-07 44 views

回答

7

FaultException<>繼承自FaultException。因此,改變你的代碼:

catch (FaultException fx) // catches all your fault exceptions 
{ 
    ... 
} 

===編輯===

如果需要FaultException<T>.Detail,你一對夫婦的選擇,但他們都不是友好的。最好的解決方案是捕捉你想要抓住的每種類型:

catch (FaultException<Foo> fx) 
{ 
    ... 
} 
catch (FaultException<Bar> fx) 
{ 
    ... 
} 
catch (FaultException fx) // catches all your other fault exceptions 
{ 
    ... 
} 

我建議你這樣做。否則,你會沉浸在思考中。

try 
{ 
    throw new FaultException<int>(5); 
} 
catch (FaultException ex) 
{ 
    Type exType = ex.GetType(); 
    if (exType.IsGenericType && exType.GetGenericTypeDefinition().Equals(typeof(FaultException<>))) 
    { 
     object o = exType.GetProperty("Detail").GetValue(ex, null); 
    } 
} 

反思是緩慢的,但由於異常被認爲是罕見的......再說,我勸突破出來,你能。

+0

但是如何訪問Detail? =)編輯問題 – SFun28 2011-06-07 18:09:39

+0

@ SFun28:我更新了我的答案。 – Amy 2011-06-07 20:28:49

+0

+1 - 謝謝!我選擇了反射方法,因爲我有許多可能引發的FaultException類型。 – SFun28 2011-06-07 21:09:45

0
catch (FaultException ex) 
{ 
    MessageFault fault = ex.CreateMessageFault(); 
    var objFaultContract = fault.GetDetail<Exception>(); 

    //you will get all attributes in objFaultContract 
}