Getting Web API Exception Details from a HttpResponseMessage

The Problem

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!

Some background

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.

Exception in browser

Same thing with fiddler, get a 500 back and you’ll even be treated to a Json version of the above.

Exception in fiddler

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.

The Solution

Instead I have added an extension method to HttpResponseMessage to parse the details of the exception from the Json in the response.Content.

 1using System.Net.Http;
 2using System.Threading.Tasks;
 3using Newtonsoft.Json;
 5namespace SimpleWebApiClient
 7    public static class HttpResponseMessageExtension
 8    {
 9        public static async Task<ExceptionResponse> ExceptionResponse(this HttpResponseMessage httpResponseMessage)
10        {
11            string responseContent = await httpResponseMessage.Content.ReadAsStringAsync();
12            ExceptionResponse exceptionResponse = JsonConvert.DeserializeObject<ExceptionResponse>(responseContent);
13            return exceptionResponse;
14        }
15    }
17    public class ExceptionResponse
18    {
19        public string Message { get; set; }
20        public string ExceptionMessage { get; set; }
21        public string ExceptionType { get; set; }
22        public string StackTrace { get; set; }
23        public ExceptionResponse InnerException { get; set; }
24    }

Usage is simple.

 1    //snip
 2    HttpResponseMessage response = await httpClient.GetAsync(query).ConfigureAwait(false);
 4    if (response.IsSuccessStatusCode)
 5        // return the value
 7    // But if an error occurred read the details           
 8    ExceptionResponse exceptionResponse = response.ExceptionResponse();
10    //snip
comments powered by Disqus