Getting Web API Exception Details from a HttpResponseMessage
It’s hard to get the details of an exception from a Web Api response when calling Web Api from a C# program. (Skip to the solution if you don’t care about the background), it even handles inner exceptions!
If you are working on a Web Api project and testing with a web browser you get a wonderful error page when an exception occurs. It gives you the message, exception message, exception type and the stack trace. Pretty much all you need to get started figuring out what has gone wrong.
Same thing with fiddler, get a
500 back and you’ll even be treated to a Json version of the above.
What about calling the action method from inside a c# program? Should be easy, you just create a client, setup the query, let it rip and examine the response for a success status and then read the content to get the returned values. Great, works fine.
What if the server threw an exception like the ones shown above, I thought it would be a simple thing to call
response.Exception or the like and get all the details. But easy it is not.
I rooted around in the
response for a while but found nothing that was simple to use.
Instead I have added an extension method to
HttpResponseMessage to parse the details of the exception from the Json in the
Usage is simple.