SOCKJS Logo
Back to Docs
Advanced

Error Handling

Handling errors and reconnection

1Connection Errors

javascript
sock.onclose = function(e) {
  if (e.code !== 1000) {
    console.error('Connection error:', e.reason);
    scheduleReconnect();
  }
};

2Auto Reconnect

javascript
let reconnectAttempts = 0;
const maxReconnectAttempts = 5;

function connect() {
  const sock = new SockJS('wss://socket-public.shockjs.app');
  
  sock.onopen = function() {
    reconnectAttempts = 0;
  };
  
  sock.onclose = function() {
    if (reconnectAttempts < maxReconnectAttempts) {
      reconnectAttempts++;
      const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
      setTimeout(connect, delay);
    }
  };
}