When use standard webHttpBinding in WCF (e.g. for RESTful endpoints) you may face with the following problem: standard error handler WebErrorHandler which ships with WebHttpBehavior returns generic “Internal Server Error” message for any exception you throw in the WCF service. Or to be more precise it returns response message which contains exception message like this:
This message if very verbose and contains a lot of useless xml noise. In order to solve these problems simple custom error handler can be used:
Here I use 2 external classes: WebException from WcfRestContrib project and ErrorBodyWriter which realization I found in one of the forum threads. WebException is very easy: is just allows you to specify HTTP status when throw exception (as far as I know in .Net 4.0 there is standard equivalent of this class for WCF):
ErrorBodyWriter is used in order to construct POX-style response body:
With this error handler you will have the following response body:
Note that instead of “Internal server error” we show actual error message also “InternalServerError: Product with the same name already exists”. We do this in the following line of code:
Client proxy generated by VS uses exactly StatusDescription for initialization of Exception.Message property. So now we will have error message at the client.
The remaining thing is to add this error handler into our service. I will show how to make it via web.config:
Here we defined custom behavior extension with custom behavior (customPoxBehavior). The following classes are used for this:
After that you will be able to use custom error handler for your WCF service.
Update 2011-06-12: with HTTPS this method can cause protocol violation exception. Here I posted solution for this problem.