Catch FaultException <TDetail> for any TDetail derived from Exception?

How can I throw a FaultException for any TDetail retrieved from Exception?
I tried catch( FaultException<Exception> ) {}, but it does not work.

Edit
The goal is to access the Detail property.

+3
source share
2 answers

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

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

=== Edit ===

If you need FaultException<T>.Detail, you have a couple of options, but none of them are friendly. The best solution is to catch every single 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 to do it like this. Otherwise, you will plunge 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);
    }
}

, ... , , .

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

    //you will get all attributes in objFaultContract
}
0

All Articles