WCF Web HTTP Error Handling

Windows Communication Foundation (WCF) Web HTTP error handling enables you to return errors from WCF Web HTTP services that specify an HTTP status code and return error details using the same format as the operation (for example, XML or JSON).

WCF Web HTTP Error Handling

The WebFaultException class defines a constructor that allows you to specify an HTTP status code. This status code is then returned to the client. A generic version of the WebFaultException class, WebFaultException<T> enables you to return a user-defined type that contains information about the error that occurred. This custom object is serialized using the format specified by the operation and returned to the client. The following example shows how to return an HTTP status code.

public string Operation1()
{
    // Operation logic  
   // ...
   throw new WebFaultException(HttpStatusCode.Forbidden);
}  

The following example shows how to return an HTTP status code and extra information in a user-defined type. MyErrorDetail is a user-defined type that contains extra information about the error that occurred.

public string Operation2()
{
   // Operation logic  
   // ...
   MyErrorDetail detail = new MyErrorDetail()
   {  
      Message = "Error Message",  
      ErrorCode = 123,  
   }  
   throw new WebFaultException<MyErrorDetail>(detail, HttpStatusCode.Forbidden);  
}  

The preceding code returns an HTTP response with the forbidden status code and a body that contains an instance of the MyErrorDetails object. The format of the MyErrorDetails object is determined by:

For more information about how these values affect the formatting of the operation, see WCF Web HTTP Formatting.

WebFaultException is a FaultException and therefore can be used as the fault exception programming model for services that expose SOAP endpoints as well as web HTTP endpoints.

See also