How to catch FaultExceptions from asynchronous WCF calls?

2.9k views Asked by At

I would like to call a wcf service that can throw FaultException, but I would like to do that asynchronously. If everything's ok, it returns no exception, but if the service throws one of my FaultExceptions, in the client I get a CommunicationObjectFaultedException and none of its properties contain my original FaultException.

From what I could learn so far about this, is that information is stored elsewhere. Can anybody please tell me where exactly it is?

For example these two handle the registration of a user:

internal void CallRegisterUser()
{
    _service.RegisterUserAsync("username", "pass");
}

void _service_RegisterUserCompleted(object sender, RegisterUserCompletedEventArgs e)
{
    if (e.Error != null) { MessageBox.Show(e.Error.Message); }
}
1

There are 1 answers

3
Julio Casal On

An oversimplified example, but this is how you would get your custom fault details:

    void client_RegisterUserCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            if (e.Error is FaultException<UserRegistrationFault>)
            {
                UserRegistrationFault fault = (e.Error as FaultException<UserRegistrationFault>).Detail;
                MessageBox.Show("Error: " + fault.TheExceptionMessage);
            }
            else
            {
                MessageBox.Show("Error: " + e.Error.ToString());
            }
        }            
    }