D
Deno

help

When the destination server is down, WebSocketStream stops and the program crashes.

Mmokyu10/14/2023
I'm running the following code:
const ws = new WebSocketStream("wss://localhost");

setInterval(() => {
console.log("test...");
}, 500);
const ws = new WebSocketStream("wss://localhost");

setInterval(() => {
console.log("test...");
}, 500);
When the localhost server is down, the code crashes and stops. With a normal WebSocket, it continues to run without stopping. How can I make it run continuously without stopping?
DAHDeno AI Helper10/14/2023
Based on the documentation, when using the WebSocketStream API, you can handle errors by wrapping your code in a try-catch block. This way, if the WebSocket connection cannot be established or if it gets interrupted, the error will be caught and your program will continue to run. Here's how you can modify your code:
async function connectWebSocket() {
try {
const ws = new WebSocketStream("wss://localhost");
const { readable, writable } = await ws.connection;
// ... rest of your WebSocket handling code ...
} catch (error) {
console.error("WebSocket error:", error);
}
}

setInterval(() => {
console.log("test...");
connectWebSocket();
}, 500);
async function connectWebSocket() {
try {
const ws = new WebSocketStream("wss://localhost");
const { readable, writable } = await ws.connection;
// ... rest of your WebSocket handling code ...
} catch (error) {
console.error("WebSocket error:", error);
}
}

setInterval(() => {
console.log("test...");
connectWebSocket();
}, 500);
In this code, we've wrapped the WebSocket connection in a function connectWebSocket(). This function is called every 500 milliseconds, along with the "test..." log. If the WebSocket connection fails, the error will be logged to the console, but the program will continue to run. Please note that this isn't explicitly mentioned in the documentation, but it's a common way to handle errors in JavaScript.

Looking for more? Join the community!