Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 17, 2022 12:14 pm GMT

Work in Progress

The purpose of this article is to give you an example of making a HTTP request in F# wrapped in a try-catch and using telemetry for error handling.

The example was built in a console application using .NET 6 and requires the below packages

Newtonsoft.Json/13.0.1Serilog/2.11.1Serilog.Sinks.Console/4.0.2

It also makes use of the free to use API placeholder service JSONPlaceholder.

Paste the below code into your Program.fs and execute.

open Systemopen System.Netopen System.Net.Httpopen System.Threadingopen System.Threading.Tasksopen Newtonsoft.Jsontype Post =    { userId: int      id: int      title: string      body: string }let DeserializePost (response: string) : Post =    JsonConvert.DeserializeObject<Post>(response)let GetItem    (client: HttpClient)    (message: HttpRequestMessage)    (ct: CancellationToken) : Task<option<Post>> =        task {                try            let! response = client.SendAsync(message, ct)            if response.StatusCode = HttpStatusCode.OK then                let! payload = response.Content.ReadAsStringAsync()                return Some (DeserializePost payload)            else                return None        with        | :? TaskCanceledException as ex -> printfn $"Task Canceled Exception: {ex.Message}"                                            return None        | :? TimeoutException as ex -> printfn $"Timeout Exception: {ex.Message}"                                       return None        | ex -> printfn $"General Exception: {ex.Message}"                return None    }let main =    let client = new HttpClient()    let tokenSource = new CancellationTokenSource(2000)    let token = tokenSource.Token    //GET    task {        let getMessage = new HttpRequestMessage(HttpMethod.Get, "https://jsonplaceholder.typicode.com/posts/1")          let! item = GetItem client getMessage token        printfn $"{item}"    }main.Wait()

Output

Some({ userId = 1  id = 1  title =   "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"  body =   "quia et suscipitsuscipit recusandae consequuntur expedita et cumreprehenderit molestiae ut ut quas totamnostrum rerum est autem sunt rem eveniet architecto" })

Further Readings

Making F# HTTP calls using either System.Net.Http, Http.Fs or Flurl -> here
Configuring Serilog into F# -> Here


Original Link: https://dev.to/robmulpeter/f-http-request-with-try-catch-logs-2l3b

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To