Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make an abstraction layer on top of Fetch to report good errors #7

Closed
MangelMaxime opened this issue Oct 2, 2019 · 0 comments
Closed

Comments

@MangelMaxime
Copy link
Contributor

MangelMaxime commented Oct 2, 2019

As an example, this is was I used in my app at work.

type FetchResult =
    | Success of Response
    | BadStatus of Response
    | NetworkError

let fetch (url: string) (init: RequestProperties list) : JS.Promise<FetchResult> =
    GlobalFetch.fetch(RequestInfo.Url url, Fetch.requestProps init)
    |> Promise.map (fun response ->
        if response.Ok then
            Success response
        else
            if response.Status < 200 || response.Status >= 300 then
                BadStatus response
            else
                NetworkError
    )

let postRecord (url: string) (body: string) (properties: RequestProperties list) =
    let defaultProps =
      [ RequestProperties.Method HttpMethod.POST
        Fetch.requestHeaders [ ContentType "application/json" ]
        RequestProperties.Body !^(body) ]

    List.append defaultProps properties
    |> fetch url
    |> Promise.bind(fun result ->
        promise {
            match result with
            | Success response -> return response
            | BadStatus response ->
                return failwith (string response.Status + " " + response.StatusText + " for URL " + response.Url)
            | NetworkError ->
                return failwith "network error"
        }
    )

The idea is that it's important to give access to the user to Response so he doesn't lose information about what happened.

We have to provide a Result<_, _> version of the "safe" requests (tryXXXX) and one which uses exceptions for the "unsafe" requests.

SCullman added a commit to SCullman/Thoth.Fetch that referenced this issue Oct 6, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant