Error Handling in WCF RESTful Service

WCF possesses the capability to handle errors for RESTful services and return an appropriate HTTP status code as well as error details using standard formats like JSON or XML. So,WebFaultException is the class that returns one of the following: 

  • HTTP status code only
  • HTTP status code and user-defined type

We can define a custom type for error details and pass it to the WebFaultException class constructor. Further, this custom type is serialized using a defined format (in other words JSON/XML) and forwarded to the client.

This WCF tutorial is part of a series on creating WCF RESTful services. In previous articles, we created RESTful services peforming all CRUD operations and later in Part 2, consuming it using jQuery. Here in this article, our focus is on error handling mechanisms supported by WCF for HTTP services. We will be referring to the previous article example here, so I recommend that you go through it first.

Now, it's quite simple to return just a HTTP status code. For example, in the previous article, we created a WCF RESTful service having a service method GetBookById. It takes a bookId as method parameter and returns a Book object against the provided bookId in JSON format. So, to return the proper HTTP status code, we can update the implementation as follows:

public Book GetBookById(string id)

{

        Book book = repository.GetBookById(int.Parse(id));

        if (book == null)

        {

            throw new WebFaultException(HttpStatusCode.NotFound);

        }

        return book;

}

But if we wanted to add some custom details with error code then we need to provide a user-defined type that holds the information. I have created a simple custom error type but you can modify it depending on your needs.

[DataContract]

public class MyCustomErrorDetail

{

    public MyCustomErrorDetail(string errorInfo, string errorDetails)

    {

        ErrorInfo = errorInfo;

        ErrorDetails = errorDetails;

    }

 

    [DataMember]

    public string ErrorInfo { get; private set; }

 

    [DataMember]

    public string ErrorDetails { get; private set; }

}

And the implementation of the same service method GetBookById will be updated accordingly as follows:

public Book GetBookById(string id)

{

   Book book = repository.GetBookById(int.Parse(id));

   if (book == null)

   {

       MyCustomErrorDetail customError = new MyCustomErrorDetail("Book not found", "No book exists against provided bookId.");

       throw new WebFaultException<MyCustomErrorDetail>(customError, HttpStatusCode.NotFound);

   }

   return book;

}

Hopefully, this article will be helpful in custom error handling for WCF RESTful services.

Up Next
    Ebook Download
    View all
    Learn
    View all