How to return JSON from a custom error handler

Topics: Web Api
Jan 26, 2012 at 10:04 AM
Edited Jan 26, 2012 at 10:09 AM

There's been discussion elsewhere that in a custom error handler which might start like this:

public class MyErrorHandler : HttpErrorHandler
        protected override bool OnTryProvideResponse(Exception exception, ref HttpResponseMessage message)

... that the message is always empty. In fact, it's up to the error handler to populate it.

I noticed that if you do this and don't attach the request to the message, then the formatters will not honour the accept headers in the request and consequently WebApi defaults to XML formatting.

To fix this, you need to manually add the request into the response with a workaround as followes. Say you are creating an HttpResponseMessage in the message variable, then :

message.RequestMessage = OperationContext.Current.RequestContext.RequestMessage.ToHttpRequestMessage();
Jan 26, 2012 at 3:12 PM

See the problem with your example, is that the OperationContext.Current doesn't always have the request context in it.

It is also highly recommended to NEVER access the static state management classes because of this reason.

This is why people are up in arms.

Jan 26, 2012 at 4:51 PM
Edited Jan 26, 2012 at 4:53 PM

I agree, it's not pretty. I was about to inject a class to wrap access to the static property in a "safe" and testable manner, but then I realised that fortunately after the custom error handler is called the reponse is passed through the message handlers in the usual manner.

With this knowledge in hand, I ended up putting in a handler that attaches the request to the response if it's missing. This is quite easy in a DelegatingHandler and it addresses the problem reasonably cleanly - at least it will do until things improve. A simiar approach could be used to "complete" the error response in the more general case where you need access to data in the request.