locked
async and await, capture exceptions when the Post is done. . RRS feed

  • Question

  • User-1825561198 posted

    using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("X-SDS-User", "test"); var json = JsonConvert.SerializeObject(MyRequest); HttpContent content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); string StringAsync = string.Empty; try { StringAsync = await client.PostAsync(_ServiceURL, content).Result.Content.ReadAsStringAsync(); Result = JsonConvert.DeserializeObject<RequestResult>(StringAsync); return Result; } catch(Exception) { } }

    In my code I am using async await which is working perfectly. The only thing is I want to be able to catch the exceptions or messages through by my service.

    How would I capture the Result as a HTTpResponseMessage?

    Could we use PutAsJSonAsync , if so how would we use it. Please help with code. I am looking to capture if the service returns exceptions when the Post is done.

    HttpResponseMessage response = await client.PutAsJsonAsync(_ServiceURL,);

    This call to the service is made from a non web application.

    Thank you

    Thursday, December 10, 2015 9:08 PM

Answers

  • User-1825561198 posted
    HttpContent content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
                    string StringAsync = string.Empty;
                    try
                    {
                        HttpResponseMessage Response = client.PostAsync(_ServiceURL, content).Result;
    
                        if (Response.IsSuccessStatusCode)
                        {
                            StringAsync = await Response.Content.ReadAsStringAsync();
                            requestResult = JsonConvert.DeserializeObject<RequestResult>(StringAsync);
    
                        }
                        if (!Response.ReasonPhrase.Contains("OK") || requestResult == null)
                        {
                            throw new Exception(Response.ReasonPhrase.ToString());
                        }
    
                        return requestResult;
                    }
                    catch (Exception ex)
                    {
                        
                    }
                    return requestResult;

    This worked for me. Is there a better way in doing this?

    Thank you for getting back.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, December 11, 2015 2:40 PM

All replies

  • User-1946294156 posted

    In the web api, I typically do this in the Catch section:

    var resp = new HttpResponseMessage(HttpStatusCode.InternalServerError)
    {
        ReasonPhrase = "Exception:" + exception.Message
    };
    throw new HttpResponseException(resp);

    Any of Call Functions (Get, Post, Put, Delete) have a Try/Catch statement with the above nicely nested into the catch statement of the call.  As you can see, I only send the message back, you can send the entire exception back.  The web APIs that I have run on a server I have access to, so before I have this code, I drop the who exception into the event log of the server. 

     You would handle the exception like this on your client side code:

    var response = httpClient.GetAsync("api/controller").Result;
    if (response.IsSuccessStatusCode)
    {
       IEnumerable<myClass> r = response.Content.ReadAsAsync<IEnumerable<myClass>>().Result;
       return r;
    }
    
    if (response.ReasonPhrase.Contains("Exception"))
    {
       throw new Exception(response.ReasonPhrase.Substring(10, response.ReasonPhrase.Length - 10));
    }
    
    throw new Exception("No Response from Server.", new Exception(response.ReasonPhrase));

    Thursday, December 10, 2015 9:25 PM
  • User-1825561198 posted
    HttpContent content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
                    string StringAsync = string.Empty;
                    try
                    {
                        HttpResponseMessage Response = client.PostAsync(_ServiceURL, content).Result;
    
                        if (Response.IsSuccessStatusCode)
                        {
                            StringAsync = await Response.Content.ReadAsStringAsync();
                            requestResult = JsonConvert.DeserializeObject<RequestResult>(StringAsync);
    
                        }
                        if (!Response.ReasonPhrase.Contains("OK") || requestResult == null)
                        {
                            throw new Exception(Response.ReasonPhrase.ToString());
                        }
    
                        return requestResult;
                    }
                    catch (Exception ex)
                    {
                        
                    }
                    return requestResult;

    This worked for me. Is there a better way in doing this?

    Thank you for getting back.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, December 11, 2015 2:40 PM