I'm trying to implement a custom error handling in web API, and I need to get the exception from the returned HttpResponseMessage.
I've tried to get exception info by from:
response.Content.ReadAsAsync<HttpError>().Result
But I can't access the result object, I'm getting an exception when trying, So I'm obviously doing it wrong.
Can't figure out how to do it, Assistance would be appreciated.
Edit:
My client code is not relevant, it's simply a GET request, server code:
Controller action throws Exception:
if (condition == true)
{
var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("Some Exception Related Message"),
ReasonPhrase = "Some More Info"
};
throw new HttpResponseException(response);
}
SendAsync method of my implemented DelegatingHandler gets the response, and this is where I want to get the callstack of the exception that was thrown in the controller action above.
errorDetails = new ResponseErrorDetailsFull
{
Message = "An error has occurred.",
ExceptionMessage = response.ReasonPhrase,
StackTrace = response.Content.ReadAsAsync<HttpError>().Result.StackTrace
};
Edit #2
Ok, So I found out that if I create a ExceptionFilterAttribute, and Override OnException(), use the attribute on my DelegatingHandler I'm able to access the exception as mentioned in the above code.
Can someone provide an explanation why this is working this way?