How to get the received exception from HttpResponseMessage (HttpStatusCode, Exception)

According to the following website, you can pass the exception parameter to the HttpResponseMessage.CreateErrorResponse method ( https://msdn.microsoft.com/en-us/library/jj127064(v=vs.118).aspx )

My question is how to get the exception information from the HttpResponseMessage created by the CreateErrorResponse method. If there is no way to get information about the exception, what is the point of overloading the method to eliminate the exception as input?

To clarify which answers I’m not looking for ... I know that I can convey a custom cause of the error in the body content ( http://weblogs.asp.net/fredriknormen/asp-net-web-api-exception-handling ), but I'm really interested to know how to use the HttpRequestMessageExtensions.CreateErrorResponse method (HttpRequestMessage method, HttpStatusCode, Exception ).

Example WebAPI controller:

Route("location/{locationName}/Databases/{databasename}/ProcedureSession")][LocationSetUp] public HttpResponseMessage Post([FromBody] ProcedureSessionData procedureSession) { try { throw new Exception("test Exception"); } catch (Exception e) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); } } 

How to get an exception in this code:

 using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); string api = "testApi/location/here/databases/testDb/ProcedureSession"; HttpResponseMessage response = client.PostAsJsonAsync(api, newSessionData).Result; if (!response.IsSuccessStatusCode) { //how can i pick up the exception object from here? //Or am I missing the point of this CreateErrorResponse overload? } 
+7
c # asp.net-web-api error-handling
source share
2 answers

To get an error message from HttpResponseMessage, you must get an HttpError object, as shown below. The HttpError object then contains ExceptionMessage, ExceptionType, and StackTrace information.

 if(!response.IsSuccessStatusCode){ HttpError error = response.Content.ReadAsAsync<HttpError>().Result; } 
+8
source

you can try using

  response.EnsureSuccessStatusCode() 

What will throw an exception if a successful response code is not received.

+3
source

All Articles