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

[Feature request] Add response.isOk to check if the response status code is 2xx #793

Open
petrpavlik opened this issue Dec 8, 2024 · 2 comments

Comments

@petrpavlik
Copy link

I believe that the community would benefit from adding a simple boolean check whether the status code of the response is acceptable.

I took inspiration from the javascript's fetch API where the response exposes response.ok to check whether the status code is >= 200 and < 300 (see the documentation), and created a simple extension to make my life easier.

extension HTTPClientResponse {
    var isOk: Bool {
        status.code >= 200 && status.code < 300
    }
}

Happy to contribute (and write tests) this if there is interest from the side of the maintainers.

@Lukasa
Copy link
Collaborator

Lukasa commented Dec 9, 2024

I don't have any particular objection to this extension, though I'm not sure how useful it actually is: 3xx responses aren't errors, and many 2xx responses are conceptually not equivalent to ok. But the weight of fetch matters a fair bit here.

@petrpavlik
Copy link
Author

petrpavlik commented Dec 9, 2024

I think that it's just a convenience abstraction over whether a successful request returns 200, 201, or what. That's how I've been using it.

My response handling usually looks something like this

if response.isOk {
  // try to parse the expected JSON
} else {
 // get the status code and try to parse the expected error JSON for 400 errors
}

This is for cases where I do not expect that a request may respond with a 3xx redirect.

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

2 participants