Pergunta

I defined a WCF Service with FaultExceptions, but the client is not catching the exceptions properly.

The contract for the exception is:

[DataContract]
public class ServiceFault {
    [DataMember]
    public string Operation { get; set; }

    [DataMember]
    public string Reason { get; set; }

    [DataMember]
    public string Message { get; set; }
}

The operation

public interface IProductsService {
    [OperationContract]
    [FaultContract(typeof(ServiceFault))]
    List<string> ListProducts();
}

In the operation I introduced an error on purpose:

    public List<string> ListProducts() {
        List<string> productsList = null;// = new List<string>();

        try {
            using (var database = new AdventureWorksEntities()) {
                var products = from product in database.Products
                               select product.ProductNumber;
                productsList.Clear(); // Introduced this error on purpose
                productsList = products.ToList();
            }
        }
        catch (Exception e) {
            throw new FaultException<ServiceFault>(new ServiceFault() {
                Operation = MethodBase.GetCurrentMethod().Name,
                Reason = "Error ocurred",
                Message = e.InnerException.Message
            });
        }

        return productsList;
    }

Then in the client app, I catch

catch (FaultException<ServiceFault> ex) {
    Console.WriteLine("FaultException<ArgumentFault>: {0} - {1} - {2}",
            ex.Detail.Operation, ex.Detail.Reason, ex.Detail.Message);

}
catch (FaultException e) {
    Console.WriteLine("{0}: {1}", e.Code.Name, e.Reason);
}

But the second catch is catching the error, so I get this message instead (although correct is not in the right form)

InternalServiceFault: Object reference not set to an instance of an object

What can I do to make the strongly typed exception catch the error?

PS: There was a similar post to this but I didn't understand it

Foi útil?

Solução

Are you sure e.InnerException is not null in Message = e.InnerException.Message?

That would lead to an unhandled NullReferenceException in the service call and thus throwing FaultException<ExceptionDetail> instead of FaultException<ServiceFault>.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top