WebSockets & Real-Time Communication

How should WebSocket error handling be implemented in production applications?
class WebSocketHandler {
    constructor(url) {
        this.url = url;
        this.reconnectAttempts = 0;
        this.connect();
    }

    connect() {
        this.ws = new WebSocket(this.url);
        this.setupErrorHandling();
    }

    setupErrorHandling() {
        this.ws.onerror = (error) => {
            console.error('WebSocket error:', error);
            this.handleError(error);
        };

        this.ws.onclose = (event) => {
            if (!event.wasClean) {
                this.handleError(new Error(`Connection closed abnormally, code: ${event.code}`));
            }
        };
    }

    handleError(error) {
        // Log to monitoring service
        this.logError(error);

        // Attempt reconnection with backoff
        if (this.shouldReconnect()) {
            this.scheduleReconnection();
        }

        // Notify application of error state
        this.emit('error', error);
    }
}
Next Question (10/17)