Search code examples
wcfexceptionfaultexception

Wcf exception handling throw an error


Hi I have a problem handling exceptions in wcf. I have a service like this one:

[ServiceContract]
public interface IAddressService
{
    [OperationContract]
    [FaultContract(typeof(ExecuteCommandException))]
    int SavePerson(string idApp, int idUser, Person person);
}

I am calling the SavePerson() on the service in the WCFTestClient utility. The SavePerson() implementation is:

public int SavePerson(string idApp, int idUser, Person person)
{
    try
    {
        this._savePersonCommand.Person = person;

        this.ExecuteCommand(idUser, idApp, this._savePersonCommand);

        return this._savePersonCommand.Person.Id;
    }
    catch (ExecuteCommandException ex)
    {
        throw new FaultException<ExecuteCommandException>(ex, new FaultReason("Error in   'SavePerson'"));
    }
}

But I get this error:

Failed to invoke the service. Possible causes: The service is offline or inaccessible; the client-side configuration does not match the proxy; the existing proxy is invalid. Refer to the stack trace for more detail. You can try to recover by starting a new proxy, restoring to default configuration, or refreshing the service.

if I change the SavePerson method and instead of:

catch (ExecuteCommandException ex)
{
    throw new FaultException<ExecuteCommandException>(ex, new FaultReason("Error in   'SavePerson'"));
}

I do

catch(Exception)
{
    throw;
}

I don't get the above error, but I only get the exception message and no inner exception. What am I doing wrong?


Solution

  • When you define the fault contract:

    [FaultContract(typeof(ExecuteCommandException))] 
    

    you must not specify an exception type. Instead, you specify a data contract of your choice to pass back any values that you deem necessary.

    For example:

    [DataContract]
    public class ExecuteCommandInfo {
        [DataMember]
        public string Message;
    }
    
    [ServiceContract]
    public interface IAddressService {
        [OperationContract]
        [FaultContract(typeof(ExecuteCommandInfo))]
        int SavePerson(string idApp, int idUser, Person person);
    }
    
    catch (ExecuteCommandException ex) { 
        throw new FaultException<ExecuteCommandInfo>(new ExecuteCommandInfo { Message = ex.Message }, new FaultReason("Error in   'SavePerson'")); 
    }