Alex Rivera | Logout

Exception handling with WCF Data Services

Asked 2010-08-17T10:58:50.280
9

I want to customize exceptions/errors thrown from my WCF Data Service, so clients get as much as possible information about what exactly went wrong/what is missing. Any thoughts on how this could be achieved?

Edit
Report

1 Answer

11

There are a few things you need to do to ensure exceptions bubble over HTTP pipe to the client .

  1. You must attribute your DataService class with the following:

    [ServiceBehavior(IncludeExceptionDetailInFaults = true)] public class MyDataService : DataService

  2. You must enable verbose errors in the configuration:

    public static void InitializeService(DataServiceConfiguration config) { config.UseVerboseErrors = true; }

It is best to throw DataServiceException within. The WCF Data Service runtime knows how to map the properties to the HTTP response and will always wrap it in a TargetInvocationException.

[WebGet]
public Entity OperationName(string id)
{
    try
    {
        //validate param
        Guid entityId;
        if (!Guid.TryParse(id, out entityId))
            throw new ArgumentException("Unable to parse to type Guid", "id");

        //operation code
    }
    catch (ArgumentException ex)
    {
        throw new DataServiceException(400, "Code", ex.Message, string.Empty, ex);
    }
}

You can then unpack this for the client consumer by overriding the HandleException in your DataService like so:

/// <summary>
/// Unpack exceptions to the consumer
/// </summary>
/// <param name="args"></param>
protected override void HandleException(HandleExceptionArgs args)
{
    if ((args.Exception is TargetInvocationException) && args.Exception.InnerException != null)
    {
        if (args.Exception.InnerException is DataServiceException)
            args.Exception = args.Exception.InnerException as DataServiceException;
        else
            args.Exception = new DataServiceException(
answered 2011-10-19T10:37:13.063

Your Answer