Error Handler Behavior

Topics: Web Api
Apr 21, 2011 at 2:52 PM
Edited Apr 21, 2011 at 2:54 PM

I'm investigating the error handler options that are in the WCF Web API, and as you known, we can create a custom error handler, inheriting from the HttpErrorHandler abstract class. Below you can see the simple example that, regardless of exception type, the HttpStatusCode is always setted to BadRequest.

public class BadRequestErrorHandler : HttpErrorHandler
{
    protected override bool OnHandleError(Exception error)
    {
        return true;
    }

    protected override HttpResponseMessage OnProvideResponse(Exception error)
    {
        return new HttpResponseMessage(HttpStatusCode.BadRequest, "some text");
    }
}

When I throw the HttpResponseException type in my service, the OnProvideResponse method is called, and my client receive BadRequest status code (400). But, when I throw any other type of exception, the OnProvideResponse method is called too, but my client ends up with an internal server error (500), including on the body of response, the HTML Page saying: "The server encountered an error processing the request...".

Looking with the .NET Reflector, I noticed that there is a handler called HttpResponseErrorHandler, that is added in ErrorHandler collection, after all my custom handlers. As the WCF executes these handlers in order that they appear inside of this collection, the built-in HttpResponseErrorHandler is the last one, and it can be changing something else inside of it.

Finally, my question: is the WCF Web API able to understand that any kind of exception should be treat as the same way? Or, like traditional WCF services, that allows to "promote" any kind of exception to FaultException.

Developer
Apr 26, 2011 at 7:49 AM

It's currently not working, but Glenn (the program manager for this feature) promised that it will work :) - see his post at http://wcf.codeplex.com/discussions/255171.

Apr 26, 2011 at 1:32 PM

Hi Carlos,

Thanks a lot.

The problem is the HttpResponseErrorHandler class that was added in ErrorHandlers collection. Creating a custom factory (HttpConfigurableServiceHostFactory), host (HttpConfigurableServiceHost) and behavior (HttpBehavior), I can remove the error handlers that were added, and to add only my custom error handler.

Anyway, as Glenn posted there (http://wcf.codeplex.com/discussions/255171), is a bug, and I'll next bits to re-test.

One more time, thanks Carlos!

Jul 8, 2011 at 7:34 AM

Is there an update on this issue?

Jul 28, 2011 at 8:17 PM

Vote up this issue: http://wcf.codeplex.com/workitem/62