Skip to content

Commit 1e45033

Browse files
authored
[Mono.Android] Wrap connection exceptions in HttpRequestException (#7661)
Fixes: #7629 Whenever a Java backend connection fails for any reason, wrap the thrown exception in `HttpRequestException` as described in the [`HttpClient.SendAsync()` documentation][0]. [0]: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.sendasync?view=net-7.0#system-net-http-httpclient-sendasync(system-net-http-httprequestmessage)
1 parent c1752ca commit 1e45033

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

src/Mono.Android/Xamarin.Android.Net/AndroidMessageHandler.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -494,7 +494,11 @@ Task ConnectAsync (HttpURLConnection httpConnection, CancellationToken ct)
494494
Logger.Log (LogLevel.Info, LOG_APP, $"Exception caught while cancelling connection: {ex}");
495495
ct.ThrowIfCancellationRequested ();
496496
}
497-
throw;
497+
498+
// All exceptions related to connectivity should be wrapped in HttpRequestException. In theory it is possible that the exception will be
499+
// thrown for another reason above, but it's OK to wrap it in HttpRequestException anyway, since we're working in the context of
500+
// `ConnectAsync` which, from the end user's point of view, is 100% related to connectivity.
501+
throw new HttpRequestException ("Connection failure", ex);
498502
}
499503
}, ct);
500504
}

tests/Mono.Android-Tests/Xamarin.Android.Net/AndroidMessageHandlerTests.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,10 +139,14 @@ private async Task AssertRejectsRemoteCertificate (Func<Task> makeRequest)
139139
Assert.Fail ("The request wasn't rejected");
140140
}
141141
#if NET
142-
catch (System.Net.WebException ex) {}
142+
// While technically we should be throwing only HttpRequestException (as per HttpClient.SendAsync docs), in reality
143+
// we need to consider legacy code that migrated to .NET and may still expect WebException. Thus, we throw both
144+
// of these and we need to catch both here
145+
catch (System.Net.WebException) {}
143146
#else
144147
catch (Java.IO.IOException) {}
145148
#endif
149+
catch (System.Net.Http.HttpRequestException) {}
146150
}
147151
}
148152
}

0 commit comments

Comments
 (0)