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#:
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
}