You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Currently, createQueryHook only exposes errors defined in the OpenAPI schema. This means that if the API returns an error defined in the schema (e.g., { message: "Invalid status" }), the error property will be typed accordingly.
However, common errors like network errors thrown by the standard fetch API result in a TypeError, which createQueryHook doesn't expose directly. This discrepancy with useSWR, which would normally capture such errors, can lead to unexpected behavior.
For example:
const{ data, error }=useQuery("/pet/findByStatus");// ^?: { message: "Invalid status" } | undefined// but If a network error occurs: TypeError
This limitation makes it difficult to handle different error scenarios and maintain type safety, especially when dealing with errors not defined in the schema.
Proposal
Add a FetcherError type parameter to createQueryBaseHook:
This is necessary!
SWR introduces a way to add status code and other information to the error returned by the fetcher as an error handling technique, but currently createQueryHook does not allow this :(
constfetcher=asyncurl=>{constres=awaitfetch(url)// If the status code is not in the range 200-299,// we still try to parse and throw it.if(!res.ok){consterror=newError('An error occurred while fetching the data.')// Attach extra info to the error object.error.info=awaitres.json()error.status=res.statusthrowerror}returnres.json()}
Description
Currently,
createQueryHook
only exposes errors defined in the OpenAPI schema. This means that if the API returns an error defined in the schema (e.g.,{ message: "Invalid status" }
), theerror
property will be typed accordingly.However, common errors like network errors thrown by the standard
fetch
API result in aTypeError
, whichcreateQueryHook
doesn't expose directly. This discrepancy withuseSWR
, which would normally capture such errors, can lead to unexpected behavior.For example:
This limitation makes it difficult to handle different error scenarios and maintain type safety, especially when dealing with errors not defined in the schema.
Proposal
Add a
FetcherError
type parameter tocreateQueryBaseHook
:createQueryBaseHook<Paths extends {}, IMediaType extends MediaType, Prefix extends string, FetcherError = never>
This allows users to specify the error type returned by the fetcher:
createQueryHook<paths, `${string}/${string}`, "<unique-key>", Error>(client, "<unique-key>")
Resulting in:
This is also beneficial for those using custom fetchers or middleware, allowing them to type their custom errors.
Extra
The text was updated successfully, but these errors were encountered: