Skip to content

Commit 95be785

Browse files
authored
Fix error schema failing to parse when field is missing from JSON response (#108)
* Make error schema work when fields are missing * Add a test * fix assertions
1 parent f9a9a63 commit 95be785

File tree

2 files changed

+52
-3
lines changed

2 files changed

+52
-3
lines changed

src/schemas/error-response.test.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import { OpenRouterErrorResponseSchema } from "./error-response";
2+
3+
describe("OpenRouterErrorResponseSchema", () => {
4+
it("should be valid without a type, code, and param", () => {
5+
const errorWithoutTypeCodeAndParam = {
6+
error: {
7+
message: "Example error message",
8+
metadata: { provider_name: "Morph" },
9+
},
10+
user_id: "example_1",
11+
};
12+
13+
const result = OpenRouterErrorResponseSchema.parse(
14+
errorWithoutTypeCodeAndParam
15+
);
16+
17+
expect(result).toEqual({
18+
error: {
19+
message: "Example error message",
20+
code: null,
21+
type: null,
22+
param: null,
23+
},
24+
});
25+
});
26+
27+
it("should be invalid with a type", () => {
28+
const errorWithType = {
29+
error: {
30+
message: "Example error message with type",
31+
type: "invalid_request_error",
32+
code: 400,
33+
param: "canBeAnything",
34+
metadata: { provider_name: "Morph" },
35+
},
36+
};
37+
38+
const result = OpenRouterErrorResponseSchema.parse(errorWithType);
39+
40+
expect(result).toEqual({
41+
error: {
42+
code: 400,
43+
message: "Example error message with type",
44+
type: "invalid_request_error",
45+
param: "canBeAnything",
46+
},
47+
});
48+
});
49+
});

src/schemas/error-response.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ import { z } from "zod/v4";
33

44
export const OpenRouterErrorResponseSchema = z.object({
55
error: z.object({
6-
code: z.union([z.string(), z.number()]).nullable(),
6+
code: z.union([z.string(), z.number()]).nullable().optional().default(null),
77
message: z.string(),
8-
type: z.string().nullable(),
9-
param: z.any().nullable(),
8+
type: z.string().nullable().optional().default(null),
9+
param: z.any().nullable().optional().default(null),
1010
}),
1111
});
1212

0 commit comments

Comments
 (0)