如何捕获任何异常派生的 TDetail 的 FaultException?
我试过catch( FaultException<Exception> ) {}
了,但这似乎不起作用。
编辑
目的是获得对 Detail 属性的访问权限。
如何捕获任何异常派生的 TDetail 的 FaultException?
我试过catch( FaultException<Exception> ) {}
了,但这似乎不起作用。
编辑
目的是获得对 Detail 属性的访问权限。
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);
}
}
反射很慢,但是由于异常应该很少见……再次,我建议您尽可能将它们分解。
catch (FaultException ex)
{
MessageFault fault = ex.CreateMessageFault();
var objFaultContract = fault.GetDetail<Exception>();
//you will get all attributes in objFaultContract
}