简体   繁体   中英

Can't catch HttpRequestException

I have following code

public async Task<T> SendData<T>()
{
    T result = default(T);

    using (var client = new HttpClient())
    {
        using (var formData = new MultipartFormDataContent())
        {
            try
            {
                foreach (var p in ParametresToSend)
                    formData.Add(p.Value, p.Key);

                HttpResponseMessage response = await client.PostAsync(URL, formData);

                string stringContent = await response.Content.ReadAsStringAsync();
                result = JsonConvert.DeserializeObject<T>(stringContent);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ParametresToSend.Clear();
            }
        }
    }

    return result;
}

It works perfectly, but if internet is not available after checks for it availability (very short time, but it possible), it catch first HttpRequestException. And after this, immediately will be throw second HttpRequestException, but catch block doesn't catch it and app geting crash. Why is it happining?

You are re-throwing the exception when you catch it, which is as good as not catching it in the first place.

Your app is crashing because there is nothing in place to handle this re-thrown exception - you do not have any global exception handling in place, which would be a very good idea if this is, itself, an ASP.NET app.

      try
        {
            HttpResponseMessage response = await client.PostAsync(URL, formData);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string stringContent = await response.Content.ReadAsStringAsync();
                result = JsonConvert.DeserializeObject<T>(stringContent);
            }
        }
        catch (HttpRequestException)
        {

            throw;
        }

try this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM