Implementing Error Handling

1. Handling Connection Errors

SourceDetection
HandshakeImmediate error + close 1006
TLSSame as above; check console
DNSSame; verify URL
Mid-streamerror followed by close

2. Handling Network Errors

Example: Online/offline awareness

window.addEventListener("offline", () => ws.close(4002, "offline"));
window.addEventListener("online",  () => reconnect());
SignalAction
navigator.onLineGate reconnect attempts
NetworkInformation APIAdapt heartbeat interval
visibilitychangePause when hidden

3. Handling Protocol Errors

Close CodeCause
1002Protocol error (e.g. bad frame)
1003Unsupported data type
1007Invalid UTF-8
1010Required extension missing

4. Handling Handshake Failures

HTTP StatusCause
401/403Auth required/denied
404Endpoint not found
426Upgrade required (wrong version)
502/503/504Proxy/upstream issue
Note: Browsers expose handshake status only via DevTools, not JS. Treat close 1006 + DevTools status as your debug pair.

5. Handling Message Parse Errors

Example: Parse-error boundary

ws.addEventListener("message", (e) => {
  let msg;
  try { msg = JSON.parse(e.data); }
  catch (err) { logger.warn("parse_error", { raw: e.data, err }); return; }
  dispatch(msg);
});
StrategyDetail
Log + dropMost resilient
Send nackRequest resend
Close socketStrict protocols only

6. Creating Custom Error Types

Example: Typed errors

class WsError extends Error { constructor(public code: number, msg: string) { super(msg); } }
class WsAuthError extends WsError {}
class WsTimeoutError extends WsError {}
ClassUse
WsAuthErrorToken rejected
WsTimeoutErrorRequest timed out
WsProtocolErrorServer violated contract

7. Implementing Error Logging

FieldReason
code/reasonFrom CloseEvent
durationConnection lifetime
retryCountReconnect attempts
userAgent / netTypeTriage
lastSendBufferedAmountBackpressure signal

8. Implementing Error Recovery

Recovery Flow

  1. Capture close code + reason
  2. Classify: recoverable / auth / fatal
  3. Refresh credentials if auth error
  4. Schedule reconnect with backoff
  5. On open: resubscribe + resync missed messages

9. Handling Buffer Overflow

DetectionAction
bufferedAmount > thresholdPause producers
Close 1009Reduce message size
Memory pressureDrop low-priority messages

10. Displaying User-Friendly Errors

StateUI Message
Connecting"Connecting…"
Reconnecting (n)"Reconnecting (attempt 3)…"
Offline"You're offline. Changes will sync."
Auth expired"Please sign in again."
Server unavailable"Service unavailable. Retrying…"