R – Customize ADO.NET Data Service Exception

ado.netexception handlingwcf-data-services

Is it possible to have a DataServiceException pass along a list of errors to consumers?

Rather than just receive the standard Message, Stacktrace information I would also like to have a list of errors when various validations fail on a model.

I tried to set the DataServiceException's inner exception to FaultException.

[DataContract]
public class MyTypeWithExtraInfo
{
   [DataMember]
   public List<MyErrorInfo> MyErrors { get; set; }
}

[DataContract]
public class MyErrorInfo
{
   [DataMember]
   string PropertyId { get; set; }

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

Clientside I do get the DataServiceException but the operation's message only has the FaultException Reason and Type (ToString'ed) it does not have the DataMembers that I have specified in MyTypeWithExtraInfo.

Best Answer

For a single exception, you can catch the actual exception and rethrow:

throw new System.ServiceMode.FaultException("Custom Error Message");

However, if you need to handle multiple exceptions, consider using the Task Parallel Library Extensions for .NET. This will allow you to collect all of the thrown exceptions and place them into a single AggregateException object. This library is slated to become part of the .NET 4.0 framework.