HttpClient sendAsync 方法中异常类型的检测

问题描述 投票:0回答:1

我正在尝试确定我遇到的异常,但所有异常都是

System.AggregateException
类型且不重要 - SSL 验证失败且主机无法访问。

HttpClient client = new HttpClient();
HttpRequestMessage httpRequestMessage = new HttpRequestMessage {
    Method = HttpMethod.Get,
    RequestUri = new Uri("https://mydomain.ru"), 
};

try {
    HttpResponseMessage httpResponseMessage = client.SendAsync(httpRequestMessage).Result;

    return ((int) httpResponseMessage.StatusCode, httpResponseMessage.Content.ReadAsStringAsync().Result);
} catch (System.Exception e) {
   // e.GetType() always return `System.AggregateException`
   return (500, $"{e.Message}; Error type: `{e.GetType().ToString()}`); 
}

存在某种方法来检测错误是什么?

httpclient maui
1个回答
0
投票
HttpClient client = new HttpClient();
HttpRequestMessage httpRequestMessage = new HttpRequestMessage {
    Method = HttpMethod.Get,
    RequestUri = new Uri("https://mydomain.ru"), 
};

try {
    HttpResponseMessage httpResponseMessage = client.SendAsync(httpRequestMessage).Result;

    return ((int) httpResponseMessage.StatusCode, httpResponseMessage.Content.ReadAsStringAsync().Result);
} catch (System.Exception e) {
    String errorMessage = "UNKNOWN CRITICAL ERROR";
    if (e is not System.AggregateException) {
        errorMessage = $"{e.Message}; Error type: `{e.GetType().ToString()}`";
    } else {
        ((AggregateException) e).Handle((x) => {
#if ANDROID
            if (e.InnerException?.InnerException is Javax.Net.Ssl.SSLHandshakeException) {
                errorMessage = "SSL validation error";
            } else if (e.InnerException?.InnerException is Java.Net.ConnectException) {
                errorMessage = "Unreachable host, check Internet connection";
            }
#elif IOS
            if (e.InnerException?.InnerException is Foundation.NSErrorException) {
                if (((Foundation.NSErrorException) e.InnerException?.InnerException)?.Code == -1202) {
                    errorMessage = "SSL validation error";
                } else if (((Foundation.NSErrorException) e.InnerException?.InnerException)?.Code == -1009) {
                    errorMessage = "Unreachable host, check Internet connection";
                }
            }
#endif

                return true;
        });
    }


   // e.GetType() always return `System.AggregateException`
   return (500, errorMessage); 
}
© www.soinside.com 2019 - 2024. All rights reserved.