Skip to content

Commit 24bb37c

Browse files
authored
feat(react-query): add includeThrownErrorsInErrorType option (#642)
1 parent 6aa64d7 commit 24bb37c

6 files changed

Lines changed: 539 additions & 76 deletions

File tree

.changeset/yellow-teachers-burn.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@ts-rest/react-query': minor
3+
---
4+
5+
RECOMMENDED: Add `includeThrownErrorsInErrorType` in react query client options. This should include the `Error` exception in the `error` type to cover non-HTTP errors such as network or CORS errors. Disabled by default so it does not break existing code, but extremely recommended to switch on.

apps/docs/docs/react-query.mdx

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,29 @@ The reason for this is error handling! Please see the [Relevant Docs](/docs/core
108108

109109
:::
110110

111+
## Error Handling
112+
113+
If a request fails, the `error` property will be set to the response from the server, or the thrown error by `fetch`. This is the same as the `data` property for successful requests.
114+
115+
By default, the type of the `error` property on the React Query hooks will only be set as `{ status: ...; body: ...; headers: ... }`, where status is a non-2xx status code, and `body`
116+
set to your response schema for status codes defined in your contract, or `unknown` for status codes not in your contract.
117+
118+
However, queries and mutations can also fail for other reasons, such as network failures, or CORS errors.
119+
In such cases, the current default behavior may cause runtime errors if you try to access the `error.(status|body|headers)` properties without first checking if the error is an instance of `Error`.
120+
121+
To include the `Error` exception type, you can set the `includeThrownErrorsInErrorType` option to `true` when initializing the client.
122+
123+
```tsx
124+
export const client = initQueryClient(router, {
125+
...,
126+
includeThrownErrorsInErrorType: true
127+
});
128+
```
129+
130+
This will force you the handle these errors if you attempt to access the `error.status` property, without first checking if the error is an instance of `Error`.
131+
132+
This will be enabled by default starting from `@ts-rest/react-query` v4.0.0.
133+
111134
## Regular Query and Mutations
112135

113136
`@ts-rest/react-query` allows for a regular fetch or mutation if you want, without having to initialise two different clients, one with `@ts-rest/core` and one with `@ts-rest/react-query`.

0 commit comments

Comments
 (0)