简体   繁体   English

httpclient异常处理

[英]httpclient exception handling

I am handing HttpRequestException when I use PostAsync and it works fine, but when I am trying to handle same exception on GetAsync it throws TaskCanceledException a task was cancelled with a long timeout instead. 我使用PostAsync时会处理HttpRequestException ,但工作正常,但是当我尝试在GetAsync上处理相同的异常时,它将抛出TaskCanceledException a task was cancelled GetAsync长时间超时而TaskCanceledException a task was cancelled How do I make GetAsync throw HttpRequestException ? 如何使GetAsync抛出HttpRequestException

  public async Task<bool> AddQrCodeToRequest(int projectId, int requestId, string code, string token)
    {
        var data = JsonConvert.SerializeObject(new { code });
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        var content = new StringContent(data, Encoding.UTF8, "application/json");
        var result = await client.PostAsync(url, content);
        if (result.IsSuccessStatusCode)
        {
            return true;
        }
        else
        {
            throw new Exception(CreateExceptionDescription(await result.Content.ReadAsStringAsync()));
        }
    }

    public async Task<List<string>> GetUpdatedQrCodesList(Request request, string token)
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        var result = await client.GetAsync(url);
        if (result.IsSuccessStatusCode)
        {
            var requestsJson = await result.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<List<string>>(requestsJson);
        }
        else
        {
            throw new Exception(CreateExceptionDescription(await result.Content.ReadAsStringAsync()));
        }
    }

handling post 处理岗位

try
{
     string QrCode = result.Text;
     if (await restService.AddQrCodeToRequest(Request, result.Text, Vars.User.Token))
     {
          QrCodes.Add(QrCode);
          await DisplayAlert("Code added", QrCode, "OK");
     }
 }
 catch (Exception ex)
 {
     if (ex is HttpRequestException)
     {
           //network ex handling
     }
     else
     {
           //other handling
     }
}

handling get (app crashes after timeout) 处理get(超时后应用崩溃)

        try
        {
            UpdatedQrCodes = await restService.GetUpdatedQrCodesList(Request, Vars.User.Token);
        }
        catch (Exception ex)
        {
            if (ex is HttpRequestException)
            {
                //never thrown
            }
            else
            {
                //never also thrown
            }
        }

As a workaround install nuget Plugin.Connectivity and before you execute your GET check if there's internet available: 解决方法是安装nuget Plugin.Connectivity,并在执行GET之前检查是否有可用的互联网:

            if (!Plugin.Connectivity.CrossConnectivity.Current.IsConnected)
            {
                // Connection not available
                throw new Exception("Not connected.");
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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