WCF possesses the capability to handle errors for RESTful services and return appropriate HTTP status code as well as error details using standard formats like JSON or XML. So, WebFaultException is the class used to return:
- HTTP status code only, or
- HTTP status code and user-defined type.
We can define a custom type for error details and pass it to WebFaultException class constructor. Further, this custom type is serialized using defined format (i.e. JSON/XML) and forwarded to the client.
::::: A Practical Guide to WCF RESTful Service :::::
This WCF tutorial is part of 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 part, our focus is on error handling mechanism supported by WCF for HTTP services. We will be referring the previous article example here, so I’ll recommend to go through it first.
Now, its quite simple to return HTTP status code only. For example in previous article, we created a WCF RESTful service having a service method GetBookById. It takes a bookId as method parameter and return Book object against provided bookId in JSON format. So, in order to return proper HTTP status code, we can update the implementation as follows:
{
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, we need to provide a user-defined type that holds the information. I have created one simple custom error type but you can modify it according to your need.
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 implementation for the same service method GetBookById will be updated accordingly as follows:
{
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(customError, HttpStatusCode.NotFound);
}
return book;
}
Hopefully, this article will helpful in custom error handling for WCF RESTful service.
Other Related Articles:
Top 10 Interview Questions and Answers Series:
- Top 10 WCF Interview Questions
- Comprehensive Series of WCF Interview Questions
- Top 10 HTML5 Interview Questions
- Top 10 ASP.NET Interview Questions
- Comprehensive Series of ASP.NET Interview Questions
- Top 10 ASP.NET MVC Interview Questions
- Top 10 ASP.NET Web API Interview Questions
- Top 10 ASP.NET AJAX Interview Questions