Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: websocket errors not catching #1126

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

amorriscode
Copy link

@amorriscode amorriscode commented Mar 12, 2025

This PR fixes a few issues related to catching websocket errors.

To reproduce, run bun run example/websocket.ts with the following code (an uncaught error occurs):

import { Elysia } from "../src";

const app = new Elysia()
	.state("start", "here")
	.ws("/ws", {
		open(ws) {
			throw new Error("asdf");
			ws.subscribe("asdf");
			console.log("Open Connection:", ws.id);
		},
		close(ws) {
			console.log("Closed Connection:", ws.id);
		},
		message(ws, message) {
			ws.publish("asdf", message);
			ws.send("asdf", message);
		},
	})
	.get("/publish/:publish", ({ params: { publish: text } }) => {
		app.server!.publish("asdf", text);

		return text;
	})
	.listen(3000, (server) => {
		console.log(`http://${server.hostname}:${server.port}`);
	});

const ws = new WebSocket('ws://localhost:3000/ws')

ws.onopen = () => {
	console.log('Connected to websocket')
	ws.send('Hello from client!')
}

ws.onmessage = (event) => {
	console.log('Received:', event.data)
}

ws.onclose = () => {
	console.log('Disconnected from websocket')
}

ws.onerror = (error) => {
	console.error('WebSocket error:', error)
}

If you modify the the code to have an onError handler above the websocket it also doesn't catch.

While on this topic: right now if there aren't any error handlers the error fails silently. Should there be a default ws error handler that closes the connection?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant