fix: bun.serve crash due to ExceptionRef (#9309)

* fix bun.serve crash due to ExceptionRef

* add test
This commit is contained in:
dave caruso
2024-03-07 18:54:15 -08:00
committed by GitHub
parent 7fc97fcf9c
commit a927340ce3
3 changed files with 50 additions and 28 deletions

View File

@@ -1,28 +0,0 @@
---
name: Upgrade an HTTP request to a WebSocket connection
---
Inside `fetch`, use the `server.upgrade()` function to upgrade an incoming `Request` to a WebSocket connection. Bun automatically returns a 101 Switching Protocols response if the upgrade succeeds.
Refer to the [WebSocket docs](/docs/api/websockets) for more information on building WebSocket servers.
```ts
const server = Bun.serve<{ authToken: string }>({
fetch(req, server) {
const success = server.upgrade(req);
if (success) {
// Bun automatically returns a 101 Switching Protocols
// if the upgrade succeeds
return undefined;
}
// handle HTTP request normally
return new Response("Hello world!");
},
websocket: {
// define websocket handlers
},
});
console.log(`Listening on localhost:\${server.port}`);
```

View File

@@ -3022,6 +3022,10 @@ pub fn serve(
return .undefined;
}
if (globalObject.hasException()) {
return .zero;
}
break :brk config_;
};

View File

@@ -432,3 +432,49 @@ test("Bun.serve().unref() works", async () => {
test("unref keeps process alive for ongoing connections", async () => {
expect([path.join(import.meta.dir, "unref-fixture-2.ts")]).toRun();
});
test("Bun does not crash when given invalid config", async () => {
const server1 = Bun.serve({
fetch(request, server) {
//
throw new Error("Should not be called");
},
port: 0,
});
const cases = [
{
fetch() {},
port: server1.port,
websocket: {},
},
{
port: server1.port,
get websocket() {
throw new Error();
},
},
{
fetch() {},
port: server1.port,
get websocket() {
throw new Error();
},
},
{
fetch() {},
port: server1.port,
get ssl() {
throw new Error();
},
},
];
for (const options of cases) {
expect(() => {
Bun.serve(options as any);
}).toThrow();
}
server1.stop();
});