From 2466d07414a3d33865f9d5312acb58ec45c47e9d Mon Sep 17 00:00:00 2001 From: Anthony Morris Date: Wed, 12 Mar 2025 11:34:26 -0700 Subject: [PATCH] fix: websocket errors not catching --- src/adapter/bun/index.ts | 20 ++++++++++---------- test/ws/message.test.ts | 29 +++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/src/adapter/bun/index.ts b/src/adapter/bun/index.ts index ff83e33a..3b95a038 100644 --- a/src/adapter/bun/index.ts +++ b/src/adapter/bun/index.ts @@ -186,9 +186,9 @@ export const BunAdapter: ElysiaAdapter = { let _id: string | undefined const errorHandlers = [ - ...(Array.isArray(options.error) + ...(options.error ? (Array.isArray(options.error) ? options.error - : [options.error]), + : [options.error]) : []), ...(app.event.error ?? []).map((x) => typeof x === 'function' ? x : x.fn ) @@ -229,9 +229,9 @@ export const BunAdapter: ElysiaAdapter = { pong(data?: unknown) { options.pong?.(data) }, - open(ws: ServerWebSocket) { + open: async (ws: ServerWebSocket) => { try { - handleResponse( + await handleResponse( ws, options.open?.( new ElysiaWS(ws, context as any) @@ -257,7 +257,7 @@ export const BunAdapter: ElysiaAdapter = { ) try { - handleResponse( + await handleResponse( ws, options.message?.( new ElysiaWS( @@ -272,9 +272,9 @@ export const BunAdapter: ElysiaAdapter = { handleErrors(ws, error) } }, - drain(ws: ServerWebSocket) { + drain: async (ws: ServerWebSocket) => { try { - handleResponse( + await handleResponse( ws, options.drain?.( new ElysiaWS(ws, context as any) @@ -284,13 +284,13 @@ export const BunAdapter: ElysiaAdapter = { handleErrors(ws, error) } }, - close( + close: async ( ws: ServerWebSocket, code: number, reason: string - ) { + ) => { try { - handleResponse( + await handleResponse( ws, options.close?.( new ElysiaWS(ws, context as any), diff --git a/test/ws/message.test.ts b/test/ws/message.test.ts index bdb324e5..4f6ecbc0 100644 --- a/test/ws/message.test.ts +++ b/test/ws/message.test.ts @@ -487,4 +487,33 @@ describe('WebSocket message', () => { await wsClosed(ws) app.stop() }) + + it('handle error with onError', async () => { + const app = new Elysia() + .onError(() => { + return 'caught' + }) + .ws('/ws', { + message(ws, message) { + throw new Error('A') + } + }) + .listen(0) + + const ws = newWebsocket(app.server!) + + await wsOpen(ws) + + const message = wsMessage(ws) + + ws.send('Hello!') + + const { type, data } = await message + + expect(type).toBe('message') + expect(data).toBe('caught') + + await wsClosed(ws) + app.stop() + }) })