Don't crash when server.fetch() is called on a server without a fetch() handler (#18151)

Co-authored-by: Ciro Spaciari <ciro.spaciari@gmail.com>
This commit is contained in:
pfg
2025-03-24 16:55:34 -07:00
committed by GitHub
parent 99ee90a58f
commit 8df7064f73
2 changed files with 15 additions and 0 deletions

View File

@@ -8003,6 +8003,11 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp
callframe: *JSC.CallFrame,
) bun.JSError!JSC.JSValue {
JSC.markBinding(@src());
if (this.config.onRequest == .zero) {
return JSPromise.rejectedPromiseValue(ctx, ZigString.init("fetch() requires the server to have a fetch handler").toErrorInstance(ctx));
}
const arguments = callframe.arguments_old(2).slice();
if (arguments.len == 0) {
const fetch_error = WebCore.Fetch.fetch_error_no_args;
@@ -8088,6 +8093,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp
var request = Request.new(existing_request);
bun.assert(this.config.onRequest != .zero); // confirmed above
const response_value = this.config.onRequest.call(
this.globalThis,
this.jsValueAssertAlive(),

View File

@@ -541,3 +541,12 @@ it("throws a validation error when routes object is undefined and fetch is not s
Learn more at https://bun.sh/docs/api/http"
`);
});
it("don't crash on server.fetch()", async () => {
await using server = Bun.serve({
port: 0,
routes: { "/test": () => new Response("test") },
});
expect(server.fetch("/test")).rejects.toThrow("fetch() requires the server to have a fetch handler");
});