@kubb/plugin-axios 6.0.3 → 6.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,25 @@
1
1
  # Handle errors
2
2
 
3
- Handle failures from the client Kubb generates. Catch a `ResponseError`, switch to a returned error result with `throwOnError`, and tell a network failure apart from a 4xx or 5xx response.
3
+ Catch a `ResponseError`, return errors as values with `throwOnError: false`, and tell a 4xx or 5xx answer apart from a request that never completed.
4
4
 
5
- The generated client throws a `ResponseError` on non-2xx responses by default:
5
+ ## What a call does
6
+
7
+ Only a non-2xx response depends on `throwOnError`:
8
+
9
+ | What happens | Result |
10
+ | ---------------------------------------- | ----------------------------------------------------------------------------------------- |
11
+ | 2xx response | Resolves with `data`. |
12
+ | Non-2xx response | Throws a `ResponseError`. With `throwOnError: false`, resolves with `error` and `status`. |
13
+ | A body fails its schema (`validator` on) | Throws a `ParseError`. |
14
+ | Invalid JSON under a JSON media type | Throws a `ParseError`. |
15
+ | Network failure, DNS failure, or timeout | Rejects with the native `AxiosError`. |
16
+ | Aborted `signal` | Rejects with the signal's reason. |
17
+
18
+ Every failure that rejects with an `Error` also reaches [`client.interceptors.error`](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/configure-requests#add-interceptors). An abort whose reason is not an `Error`, such as `abort('canceled')`, skips it.
19
+
20
+ ## Catch a ResponseError
21
+
22
+ Narrow with `ResponseError.is(error)` instead of `instanceof`, because each generated package bundles its own `ResponseError` class:
6
23
 
7
24
  ```typescript
8
25
  import { getPetById } from './gen/clients/getPetById'
@@ -10,39 +27,31 @@ import { ResponseError } from './gen/.kubb/client'
10
27
 
11
28
  try {
12
29
  const { data } = await getPetById({ path: { petId: 1 } })
13
- console.info(data)
14
30
  } catch (error) {
15
- if (ResponseError.is(error)) {
16
- console.error(error.status) // 404
17
- console.error(error.data) // the parsed error body
18
- }
31
+ if (ResponseError.is(error)) console.error(error.status, error.data) // 404, the parsed error body
19
32
  }
20
33
  ```
21
34
 
22
- The examples set [`integerType: 'number'`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#integertype) on the adapter, so an `int64` id such as `petId` is a `number`. With the default it is a `bigint` and the call takes `1n`.
23
-
24
- The `message` holds the HTTP method and the URL without its query string, so query credentials stay out of logs. For example: `GET https://api.example.com/pets/1 failed with status 404 Not Found`.
25
-
26
- The error exposes these fields:
27
-
28
35
  ```typescript
29
36
  class ResponseError extends Error {
30
- static is(error: unknown): error is ResponseError<unknown, unknown, unknown>
31
37
  data: TError // the parsed error body
32
38
  status: number
33
39
  statusText: string
34
40
  contentType: string | undefined
35
- headers: Headers
41
+ headers: Headers // such as error.headers.get('Retry-After')
36
42
  request: AxiosRequestConfig
37
43
  response: AxiosResponse
38
44
  }
39
45
  ```
40
46
 
41
- Each generated package bundles its own `ResponseError` class, so narrow with `ResponseError.is(error)` instead of `instanceof`. `is()` checks the error name.
47
+ The `message` leaves out the query string: `GET https://api.example.com/pets/1 failed with status 404 Not Found`. `request` and `response` keep the full URL, so redact them before you log the whole error.
48
+
49
+ > [!NOTE]
50
+ > The examples set [`integerType: 'number'`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#integertype). With the default `bigint`, an `int64` id takes `1n`.
42
51
 
43
52
  ## Narrow a thrown error by status
44
53
 
45
- `isResponseError<Responses>(error)` narrows a caught error to the `ResponseError` of one operation. Checking `status` then narrows `data` to the body declared for that status. A range key such as `4xx` covers its statuses that have no entry of their own, and `default` covers the rest:
54
+ `isResponseError<Responses>(error)` narrows a caught error to one operation's `ResponseError`. A check on `status` then narrows `data`. For range keys such as `4xx`, see [Status ranges](#status-ranges):
46
55
 
47
56
  ```typescript
48
57
  import { isResponseError } from './gen/.kubb/client'
@@ -57,106 +66,89 @@ try {
57
66
  }
58
67
  ```
59
68
 
60
- The type argument is not checked at runtime, so keep the `try` around one operation.
61
-
62
- The error also carries the response's `Headers` as `error.headers`, so `error.headers.get('Retry-After')` reads the same on every transport.
69
+ > [!WARNING]
70
+ > The type argument is not checked at runtime, so keep the `try` around one operation.
63
71
 
64
72
  ## Return the error instead
65
73
 
66
- Pass `throwOnError: false` and the call resolves for every documented status. The result is a
67
- discriminated union: `data` is set on success and `error` on failure. A failed call with an empty
68
- body sets `error` to `{ status, statusText }`.
69
-
70
- Check `data` before you read it. A check on `status` narrows `data` too, unless the operation
71
- declares a `default` response, whose status can be any number:
74
+ With `throwOnError: false`, the call resolves for every status. `data` is set on success and `error` on failure, and a check on `status` narrows both:
72
75
 
73
76
  ```typescript
74
77
  const result = await getPetById({ path: { petId: 1 }, throwOnError: false })
75
78
 
76
- if (result.data !== undefined) {
77
- console.info(result.data)
78
- } else {
79
- console.error(result.status, result.error)
80
- }
79
+ if (result.error !== undefined) console.error(result.status, result.error)
80
+ else console.info(result.data)
81
81
  ```
82
82
 
83
+ See [Empty error bodies and default responses](#empty-error-bodies-and-default-responses).
84
+
83
85
  ## Set the generated default
84
86
 
85
- Set `throwOnErrorDefault` on the client plugin to choose how generated operations handle non-2xx
86
- responses by default. Each call can still override that setting with `throwOnError`:
87
+ [`throwOnErrorDefault`](https://kubb.dev/extensions/kubb-labs/plugin-axios/options#throwonerrordefault) on the plugin sets what a call does when it leaves `throwOnError` out. `client.setConfig({ throwOnError })` does not change it:
87
88
 
88
89
  ```typescript
89
- import { pluginAxios } from '@kubb/plugin-axios'
90
-
91
90
  pluginAxios({ throwOnErrorDefault: false })
92
91
 
93
- // resolves with an error result
94
- const list = await searchPets({ query: { status: 'available' } })
95
-
96
- // opt one call back into throwing
97
- const pet = await getPetById({ path: { petId: 1 }, throwOnError: true })
92
+ const list = await searchPets({ query: { status: 'available' } }) // resolves with an error result
93
+ const pet = await getPetById({ path: { petId: 1 }, throwOnError: true }) // throws
98
94
  ```
99
95
 
100
- `client.setConfig({ throwOnError })` does not change this default, because each generated
101
- operation passes its own value. Set it on the plugin.
102
-
103
- ## Network failures still throw
104
-
105
- > [!IMPORTANT]
106
- > `throwOnError` only applies when the server answers. A dropped connection, a DNS failure, or an
107
- > aborted `AbortSignal` always rejects. A `ResponseError` means the server answered with a non-2xx
108
- > status, and a `ParseError` means a body failed validation or is not valid JSON. Any other error
109
- > usually means the request never completed. All of them reach `client.interceptors.error`.
110
-
111
- ```typescript
112
- try {
113
- const { data } = await getPetById({ path: { petId: 1 }, throwOnError: false })
114
- use(data)
115
- } catch (error) {
116
- // not a ResponseError: the request never completed
117
- console.error('request failed to send', error)
118
- }
119
- ```
120
-
121
- Pass an `AbortSignal` to cancel a request. The call rejects with the abort reason.
122
-
123
96
  ## Validation failures
124
97
 
125
- When you turn on the `validator` option, a body that does not match its Zod schema throws a
126
- `ParseError` instead of returning. It carries the schema's raw `issues`:
98
+ With [`validator`](https://kubb.dev/extensions/kubb-labs/plugin-axios/options#validator) on, a body that does not match its Zod schema throws a `ParseError` with the schema's `issues`:
127
99
 
128
100
  ```typescript
129
101
  import { ParseError } from './gen/.kubb/standardSchema'
130
102
 
131
103
  try {
132
- const { data } = await getPetById({ path: { petId: 1 } })
133
- use(data)
104
+ await getPetById({ path: { petId: 1 } })
134
105
  } catch (error) {
135
- if (error instanceof ParseError) {
136
- console.error(error.issues) // [{ message, path }]
137
- }
106
+ if (error instanceof ParseError) console.error(error.issues) // [{ message, path }]
138
107
  }
139
108
  ```
140
109
 
141
- A `ParseError` reports schema validation issues. A `ResponseError` reports a non-2xx status. The error body of a non-2xx response is checked against the schema of its status, then of its range such as `5xx`, then of `default`. An error body that fails its schema throws a `ParseError` in place of the `ResponseError`, also with `throwOnError: false`. A status the document leaves out, such as a `502` from a gateway, keeps its body unchecked.
110
+ To recover, pass `onValidationError` on the call or the client. Return `{ value }` to use that value, or nothing to throw the `ParseError`:
142
111
 
143
- Calling `.unwrap()` on a `throwOnError: false` call turns that same `error` into a rejection, so a
144
- `try`/`catch` works there too.
112
+ ```typescript
113
+ client.setConfig({
114
+ onValidationError: (error, { direction, source, value }) => {
115
+ console.warn(direction, source, error.issues)
116
+ return { value }
117
+ },
118
+ })
119
+ ```
120
+
121
+ For which schema checks an error body, see [Error body validation](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/serialization#error-body-validation).
145
122
 
146
123
  ## Turn validation off at runtime
147
124
 
148
- The `validator` option decides at generation time which schemas each call carries. Set `validate` on the client to skip them at runtime, for example in production or in tests with partial fixtures:
125
+ `validator` decides at generation time which schemas a call carries. `validate` skips them at runtime, for example in production or in tests with partial fixtures:
149
126
 
150
127
  ```typescript
151
- import { client } from './gen/.kubb/client'
152
-
153
128
  client.setConfig({ validate: import.meta.env.DEV })
129
+ client.setConfig({ validate: { response: false } }) // skip one direction
154
130
  ```
155
131
 
156
- `validate: false` skips every schema. An object skips only the directions set to `false`: `request` (the body), `params` (path, query, header, and cookie params), `response`, and `error`:
132
+ The default is `true`. The object form skips each direction set to `false`: `request` (the body), `params`, `response`, or `error`. A per-call `validate` overrides the client.
157
133
 
158
- ```typescript
159
- client.setConfig({ validate: { response: false } })
160
- ```
134
+ ## Less common cases
135
+
136
+ ### Status ranges
137
+
138
+ When an operation declares a range key such as `4xx`, the range covers its statuses that have no entry of their own, and `default` covers the rest.
139
+
140
+ ### Empty error bodies and default responses
141
+
142
+ When a failed call has an empty body, `error` is `{ status, statusText }`.
143
+
144
+ When the operation declares a `default` response, a check on `status` does not narrow `data` and `error`, because a `default` status can be any number. To get the success body with the default `returnType: 'full'`, call `.unwrap()`, which turns `error` into a rejection. With `returnType: 'data'`, the call returns a plain promise without `.unwrap()`.
145
+
146
+ ### Where the `throwOnError` default comes from
147
+
148
+ When you set `client.setConfig({ throwOnError })`, generated calls ignore it, because each generated function passes its own value: the call's `throwOnError`, or else [`throwOnErrorDefault`](https://kubb.dev/extensions/kubb-labs/plugin-axios/options#throwonerrordefault). That value is also the default of the function's `ThrowOnError` type parameter.
149
+
150
+ ### Read headers with `returnType: 'data'`
151
+
152
+ When the plugin sets [`returnType: 'data'`](https://kubb.dev/extensions/kubb-labs/plugin-axios/options#returntype), a call resolves to the success body alone. To read a header such as `ETag`, pass `throwOnError: false` and call `result.headers.get('etag')`. For a stream call, see [Event IDs when you resume](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/server-sent-events#event-ids-when-you-resume).
161
153
 
162
- A per-call `validate` overrides the client setting, such as `getPetById({ path: { petId: 1 }, validate: true })`. The default is `true`.
154
+ The query plugins and `@kubb/plugin-mcp` read `returnType` too, including a per-operation value from [`override`](https://kubb.dev/docs/5.x/reference/plugin-options#override).