4

How do I catch FaultException for any Exception derived TDetail?
I tried catch( FaultException<Exception> ) {} but that does not seem to work.

Edit
The purpose is to gain access to the Detail property.

Suraj
  • 35,905
  • 47
  • 139
  • 250

2 Answers2

9

FaultException<> inherits from FaultException. So change your code to:

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

=== Edit ===

If you need FaultException<T>.Detail, you've a couple of options but none of them are friendly. The best solution is to catch each individual type you want to catch:

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

I advise you do it like that. Otherwise, you're going to dip into reflection.

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

Reflection is slow, but since exceptions are supposed to be rare... again, I advise breaking them out as you are able to.

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

    //you will get all attributes in objFaultContract
}
Pang
  • 9,564
  • 146
  • 81
  • 122