How can I retrieve passed exception from HttpRespo

2019-02-21 23:56发布

问题:

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

My question is how can I retrieve the exception information from the HttpResponseMessage created by the CreateErrorResponse method. If there is not way to get the exception information, what is the point of having a method overload for taking an exception as an input?

To clarify on what answers I am not looking for... I know that I can pass a customized error reason in the content of the body (http://weblogs.asp.net/fredriknormen/asp-net-web-api-exception-handling) but I am really just curious about how to use the HttpRequestMessageExtensions.CreateErrorResponse Method (HttpRequestMessage, HttpStatusCode, Exception) method overload.

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 do I pick up the 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?
    }

回答1:

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

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


回答2:

you could try using

 response.EnsureSuccessStatusCode()

Which will throw an exception if a successful response code isn't received.