Skip to content

Commit bb02409

Browse files
fix(handler): handle invalid input in handler.fetch()
handler.fetch(null), handler.fetch(undefined), and handler.fetch(123) would throw an unhandled TypeError instead of returning an error response. Now validates the input before processing and returns a 500 response with the error details for invalid inputs. Closes #1254 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 5da2989 commit bb02409

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/handler.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,9 @@ function handlerWithFetch<
107107
}
108108
return Object.assign(handler, {
109109
fetch: (req: ServerRequest | URL | string): Promise<Response> => {
110+
if (!req || (typeof req !== "string" && typeof req !== "object")) {
111+
return Promise.resolve(toResponse(new TypeError("Invalid fetch input", { cause: req }), new H3Event(new Request("http://_"))));
112+
}
110113
if (typeof req === "string") {
111114
req = new URL(req, "http://_");
112115
}

test/handler.test.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,26 @@ describe("handler.ts", () => {
3939
});
4040
});
4141

42+
describe("handler.fetch with invalid input", () => {
43+
it("returns 500 response for null input", async () => {
44+
const handler = defineHandler(() => "ok");
45+
const res = await handler.fetch(null as any);
46+
expect(res.status).toBe(500);
47+
});
48+
49+
it("returns 500 response for undefined input", async () => {
50+
const handler = defineHandler(() => "ok");
51+
const res = await handler.fetch(undefined as any);
52+
expect(res.status).toBe(500);
53+
});
54+
55+
it("returns 500 response for numeric input", async () => {
56+
const handler = defineHandler(() => "ok");
57+
const res = await handler.fetch(123 as any);
58+
expect(res.status).toBe(500);
59+
});
60+
});
61+
4262
describe("dynamicEventHandler", () => {
4363
it("should call the initial handler if set", async () => {
4464
const initialHandler = vi.fn(async (_: H3Event) => "initial");

0 commit comments

Comments
 (0)