Custom WebFaultException on WCF Rest Serialization Failure?
With an object like this:
[DataContract]
public class SampleItem
{
private int _id;
[DataMember(IsRequired = true)]
public int Id
{
get { return _id; }
set { _id = value; }
开发者_如何学Python}
private string _stringValue;
[DataMember()]
public string StringValue
{
get { return _stringValue; }
set { _stringValue = value; }
}
And a REST call like this:
[WebInvoke(UriTemplate = "", Method = "POST")]
public SampleItem Create(SampleItem instance)
{
if (instance == null)
throw new WebFaultException<string>("The SampleItem returned wasn't correctly formatted.",
HttpStatusCode.BadRequest);
return instance;
}
If I call it with an invalid SampleItem, say something without an ID like this:
<SampleItem xmlns="http://schemas.datacontract.org/2004/07/UserWebServices" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><StringValue>SingleItem</StringValue></SampleItem>
Then the server gives me a 400 (correct) back with no useful error info (all I get is this: The server encountered an error processing the request. See server logs for more details). Ideally I want it to say something like ID is required.
How do I intercept the place where this error is being generated and throw my own WebFaultException?
Check out the WebProtocolException from the REST Start Kit. You can then send back a custom error message in your exception like this:
catch (Exception ex)
{
throw new WebProtocolException(HttpStatusCode.InternalServerError, "Unexpected Error.", new ServiceFault { ExceptionDetail = "Your custom error message here" }, null);
}
精彩评论