2

I'm creating an "SDK/Proxy" class using HttpClient and would like to pass exceptions thrown by the service the SDK is consuming to the application that is using this SDK. The original exception needs to be preserved unaltered and not wrapped. I've tried EnsureSuccessStatusCode() but it is no good because the original exception is lost to the consumer. Below is SDK code that is attempting to catch exceptions from base service and pass it on to the consumer;

public async Task<string> GetValue(string effect)
{
    using (var client = GetHttpClient())
    {
        HttpResponseMessage resp = await client.GetAsync("api/values?effect=" + effect).ConfigureAwait(false);

        if (resp.IsSuccessStatusCode)
        {
            return await resp.Content.ReadAsStringAsync();
        }
        throw await resp.Content.ReadAsAsync<Exception>();
    }
}

The "consumer" service is using the SDK like so;

public async Task<string> Get(string effect)
{
    return await baseSvc.GetValue(effect);
}

When testing this I am getting the following response;

{ Message: "An error has occurred." ExceptionMessage: "Member 'ClassName' was not found." ExceptionType: "System.Runtime.Serialization.SerializationException"...

the base service code throwing the exception is this;

public async Task<string> Get(string effect)
{
    switch (effect.ToLower())
    {
        case "string":
            return "this is a string";
        case "exception":
            throw new ApplicationException("this is an application exception.");
        default:
            return "effect requested does not exist.";
    }
}

Is it possible to "flow" the original unaltered exception from the consumed service through the SDK to the consumer?

1 Answers1

2

You can use following. string responseBody = response.Content.ReadAsStringAync().Result; throw new HttpException((int)response.StatusCode, responseBody);

I have referred this - web API and MVC exception handling

Community
  • 1
  • 1
Arindam Nayak
  • 7,346
  • 4
  • 32
  • 48
  • 2
    This is helpful, in that it offers an alternative, and I appreciate the help. It is not an answer to my question which is essentially whether or not it is possible to deserialize an ApplicationException (specifically). It would be ideal if the fact that an http call was made did not change the way exceptions "work", for example if the web api code threw a sqlexception the consumer using the SDK would receive a sqlexception rather than an httpexception. – user1783711 Dec 01 '14 at 14:57