@manhng

Welcome to my blog!

Exception in Web API

October 6, 2017 01:24

Getting Web API Exception Details from a HttpResponseMessage

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

using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace SimpleWebApiClient
{
public static class HttpResponseMessageExtension
{
public static async Task<ExceptionResponse> ExceptionResponse(this HttpResponseMessage httpResponseMessage)
{
string responseContent = await httpResponseMessage.Content.ReadAsStringAsync();
ExceptionResponse exceptionResponse = JsonConvert.DeserializeObject<ExceptionResponse>(responseContent);
return exceptionResponse;
}
}

public class ExceptionResponse
{
public string Message { get; set; }
public string ExceptionMessage { get; set; }
public string ExceptionType { get; set; }
public string StackTrace { get; set; }
public ExceptionResponse InnerException { get; set; }
}
}

Usage is simple

HttpResponseMessage response = await httpClient.GetAsync(query).ConfigureAwait(false);

if (response.IsSuccessStatusCode)
// return the value

// But if an error occurred read the details
ExceptionResponse exceptionResponse = response.ExceptionResponse();

Categories

Recent posts