Skip to content

Commit 9098b03

Browse files
committed
feat: throw understandable formatted errors
1 parent 23a2cec commit 9098b03

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

src/index.ts

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,16 +48,34 @@ function createHandler<
4848
rawInput?: I extends z.ZodType ? z.infer<I> : never
4949
) {
5050
const parsedInput = inputSchema
51-
? await inputSchema.parseAsync(rawInput)
51+
? await inputSchema.safeParseAsync(rawInput)
5252
: undefined;
5353

54+
if (parsedInput && !parsedInput.success) {
55+
const errors = z.flattenError(parsedInput.error);
56+
throw new Error(
57+
`Input doesn't match schema:\n${JSON.stringify(errors, null, 2)}`
58+
);
59+
}
60+
5461
const result = await fn.call(this, {
5562
env: this.env,
5663
ctx: this.ctx,
57-
input: parsedInput,
64+
input: parsedInput?.data,
5865
} as ImplArgs<I, Env>);
5966

60-
return outputSchema ? await outputSchema.parseAsync(result) : result;
67+
if (!outputSchema) return result;
68+
69+
const parsedOutput = await outputSchema.safeParseAsync(result);
70+
71+
if (!parsedOutput.success) {
72+
const errors = z.flattenError(parsedOutput.error);
73+
throw new Error(
74+
`Output doesn't match schema:\n${JSON.stringify(errors, null, 2)}`
75+
);
76+
}
77+
78+
return parsedOutput.data;
6179
};
6280

6381
const handlerWithDef = Object.defineProperties(handler, {
@@ -69,10 +87,14 @@ function createHandler<
6987
meta: meta ?? {},
7088
},
7189
enumerable: true,
90+
writable: true,
91+
configurable: true,
7292
},
7393
[SafeRpcMethodSymbol]: {
7494
value: true,
7595
enumerable: true,
96+
writable: true,
97+
configurable: true,
7698
},
7799
});
78100

0 commit comments

Comments
 (0)