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
@@ -181,26 +181,27 @@ For example, if you want to have a default values for an error, you should use t
181
181
zagora()
182
182
.input(z.any())
183
183
.errors({
184
-
fetchError: z.object({
184
+
FETCH_ERR: z.object({
185
+
type: z.literal('FETCH_ERR')
185
186
message: z.string().default("Unknown error"),
186
187
code: z.number().default(500),
187
188
}),
188
189
})
189
190
.handler((_, err) => {
190
-
throwerr.fetchError({
191
+
throwerr.FETCH_ERR({
191
192
message: 'Custom message',
192
193
foo: 123// type-error, no such property!
193
194
});
194
195
})
195
196
```
196
197
197
-
If you did `fetchError: z.object().default()`, you would not get type-error if you made a typo mistake when you "called" the error. The following code WILL NOT report a type-error:
198
+
If you did `FETCH_ERR: z.object().default()`, you would not get type-error if you made a typo mistake when you "called" the error. The following code WILL NOT report a type-error:
198
199
199
200
```ts
200
201
zagora()
201
202
.input(z.any())
202
203
.errors({
203
-
fetchError: z
204
+
FETCH_ERR: z
204
205
.object({
205
206
message: z.string(),
206
207
code: z.number(),
@@ -211,7 +212,7 @@ zagora()
211
212
}),
212
213
})
213
214
.handler((_, err) => {
214
-
throwerr.fetchError({
215
+
throwerr.FETCH_ERR({
215
216
mssage: 'Custom message', // typo, but not reported
216
217
foo: 123// no such key, but no type-error reported either
217
218
});
@@ -246,7 +247,12 @@ console.log({ res });
246
247
247
248
### Note on error discriminated unions
248
249
249
-
It's always a good practice to use a consistent naming convention for error types. We use the error's `type` property as discriminator. If you do not provide it in the error schema, you will not be able to discriminate between different error types. The error schema "keys" are used as helper names.
250
+
It's always a good practice to use a consistent naming convention for error types. We use the error's `type` property as discriminator. If you do not provide it in the error schema, you will not be able to discriminate between different error types. The `type` property should also match the error key, eg. you will get validation error if it's `someErr: z.object({ type: z.literal("SOME_ERR") })`, because both would mismatch.
251
+
252
+
**So here are 2 rules of thumb:**
253
+
254
+
1. Always add the `type` property in the error schema object.
255
+
2. Always make sure both the schema key and the `type` property in the schema match.
0 commit comments