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);
}
}
Production WebSocket error handling should include: 1) Comprehensive error detection and classification, 2) Structured error logging and monitoring, 3) Intelligent reconnection strategies with backoff, 4) User notification mechanisms, 5) Resource cleanup on errors, 6) Circuit breaker implementation for persistent issues, 7) Error reporting to monitoring services, 8) Fallback mechanisms when appropriate. The code demonstrates a robust error handling implementation with proper separation of concerns and recovery strategies.