Summary:
In a WCF REST service how can I handle incorrect input parameters using my own custom fault response?
Detail:
I have the following interface method in a WCF REST service:
[OperationContract]
[WebGet(UriTemplate = "getitem?id={itemId}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
[FaultContract(typeof(DataModel.Fault))]
DataModel.Item GetItem(int itemId);
Within my implementation of the GetItem method I catch any error conditions (i.e. item doesn’t exist) and create a WebFaultException. This works without any issues whatsoever.
However, lets say the invoking client calls the following url:
http://myserver.com/itemservice/getitem?id=abc
i.e. the input value for id cannot be cast to int as required by the GetItem method
This call rightly fails as the given id value is not castable to int, however this failure occurs before any of my code is executed and therefore I cannot return my DataModel.Fault object as per the FaultContract assigned to the interface method.
So the question is, how can I hook a high level error handler to catch errors of this type and subsequently return my own fault structure rather than the HTML error that WCF generates:
Request Error
The server encountered an error processing the request. See server logs for more details.
As a continuation of the same question I would also like to be able to do the same thing if the client calls the following:
http://myserver.com/itemservice/gettitem?id=abc
notice the typo in the URI, gettitem (two t’s) instead of getitem
Use
IErrorHandlerinterface to extend your service.This will allow you to provide appropriate fault for any exception.
This post shows how to hook up your own error handler to your service behavior.
I personally use single class to implement all necessary elements like this:
and web.config I extend with: