I'm new to F# and stuck in understanding async in F# from the perspective of a C# developer. Say having the following snippet in C#:
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
How to write the same in F#?
Just my two cents. But my understanding is that we should be handling the HttpRequestException
when using EnsureSuccessStatusCode()
.
Below is the start of a module wrapping HttpClient
that will buffer the response of a URL into a string
and safely wrap in a Result<'a, 'b>
for improved fault tolerance.
module Http =
open System
open System.Net.Http
let getStringAsync url =
async {
let httpClient = new HttpClient()
// This can be easily be made into a HttpClientFactory.Create() call
// if you're using >= netcore2.1
try
use! resp = httpClient.GetAsync(Uri(url), HttpCompletionOption.ResponseHeadersRead) |> Async.AwaitTask
resp.EnsureSuccessStatusCode |> ignore
let! str = resp.Content.ReadAsStringAsync() |> Async.AwaitTask
return Ok str
with
| :? HttpRequestException as ex -> return ex.Message |> Error
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With