openapi-typescript
openapi-typescript copied to clipboard
Handle error codes and failed request in error
Description Currently in order to handle errors the code usually looks something like this:
const { data, error } = get('url/which/fails/to/fetch')
.catch(error => ({error, response: new Response()}))
console.log(error) //=> TypeError: Failed to fetch
This is because a failed fetch is not getting caught by the library. Which can also lead to Typescript not liking the new possible return type introduced by the catch.
Proposal
Instead this would be nicer:
const { data, error } = get('url/which/fails/to/fetch')
console.log(error) //=> TypeError: Failed to fetch
I am not sure if I am simply doing something wrong, but having to do error handling twice can complicate things quite a lot.
The downside to this approach is that the previously unhandled errors cannot be typechecked/ However, they need to be handled in both cases anyway.
Checklist
- [x] I’m willing to open a PR for this (see CONTRIBUTING.md)
Thanks for the suggestion. I’m a little hesitant to deviate from the default fetch behavior too much, which this library implements. If this library throws, then fetch() itself threw, which “shouldn’t happen”™.
But to your point, this library is meant to provide better quality of life improvements over the default fetch spec. That’s probably in the form of clearer documentation here.
I second this, after having used some time debugging why the client middleware onResponse() handler would not fire for a redirected response which produced the same TypeError: Failed to fetch.
In this case my response would never be defined because of the error, which would require a catch handler on every request, or with a custom fetch function in the ClientOptions that catches every request.
The latter is what I currently use, but it was not obvious to me, and a more intuitive solution could be to add a middleware option like onError(), to control what happens when errors occur, and the onResponse() is never reached. Might be easily confused with http error codes though.