cognitedata / oryx

.NET Cross platform and highly composable middleware for building web request handlers in F#
Apache License 2.0
202 stars 10 forks source link

Add `withErrorCancellable` #110

Open xperiandri opened 1 year ago

xperiandri commented 1 year ago
/// Error handler for decoding fetch responses into an user defined error type. Will ignore successful responses.
let withErrorCancellable
    (errorHandler: HttpResponse -> HttpContent -> CancellationToken -> Task<exn>)
    (source: HttpHandler<HttpContent>)
    : HttpHandler<HttpContent> =
    fun next ->
        { new IHttpNext<HttpContent> with
            member _.OnSuccessAsync(ctx, content) =
                task {
                    let response = ctx.Response

                    match response.IsSuccessStatusCode with
                    | true -> return! next.OnSuccessAsync(ctx, content)
                    | false ->
                        ctx.Request.Metrics.Counter Metric.FetchErrorInc ctx.Request.Labels 1L

                        let! err = errorHandler response content ctx.Request.CancellationToken
                        return! next.OnErrorAsync(ctx, HttpException(ctx, err))
                }

            member _.OnErrorAsync(ctx, exn) = next.OnErrorAsync(ctx, exn)
            member _.OnCancelAsync(ctx) = next.OnCancelAsync(ctx) }
        |> source