Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I retrieve passed exception from HttpResponseMessage(HttpStatusCode, Exception)

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?
    }
like image 544
geohnH Avatar asked Mar 04 '15 21:03

geohnH


People also ask

How do I return an exception from Web API?

Return InternalServerError for Handled Exceptionscs file and locate the Get(int id) method. Add the same three lines within a try... catch block, as shown in Listing 2, to simulate an error. Create two catch blocks: one to handle a DivideByZeroException and one to handle a generic Exception object.

What are the different ways to handle errors in Web API?

You can customize how Web API handles exceptions by writing an exception filter. An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception.

What is the method to throw exception when HTTP call is not success?

If you prefer to treat HTTP error codes as exceptions, call HttpResponseMessage. EnsureSuccessStatusCode on the response object. This method throws an exception if the status code falls outside the range 200–299.

What is the correct syntax for throwing a HTTP response exception?

ResponseStatusException, constructor arguments: status – an HTTP status set to the HTTP response. reason – a message explaining the exception set to the HTTP response. cause – a Throwable cause of the ResponseStatusException.


1 Answers

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;
}
like image 156
geohnH Avatar answered Oct 06 '22 19:10

geohnH