openapi-typescript
openapi-typescript copied to clipboard
Allow Custom Error Types in createQueryHook for Enhanced Error Handling
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" }), 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:
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:
const { data, error } = useQuery("/pet/findByStatus");
// ^?: { message: "Invalid status" } | Error | undefined
This is also beneficial for those using custom fetchers or middleware, allowing them to type their custom errors.
Extra
- [x] I’m willing to open a PR (see CONTRIBUTING.md)