Implementing Error Handling
1. Handling Connection Errors
| Source | Detection |
| Handshake | Immediate error + close 1006 |
| TLS | Same as above; check console |
| DNS | Same; verify URL |
| Mid-stream | error followed by close |
2. Handling Network Errors
Example: Online/offline awareness
window.addEventListener("offline", () => ws.close(4002, "offline"));
window.addEventListener("online", () => reconnect());
| Signal | Action |
navigator.onLine | Gate reconnect attempts |
| NetworkInformation API | Adapt heartbeat interval |
| visibilitychange | Pause when hidden |
3. Handling Protocol Errors
| Close Code | Cause |
| 1002 | Protocol error (e.g. bad frame) |
| 1003 | Unsupported data type |
| 1007 | Invalid UTF-8 |
| 1010 | Required extension missing |
4. Handling Handshake Failures
| HTTP Status | Cause |
| 401/403 | Auth required/denied |
| 404 | Endpoint not found |
| 426 | Upgrade required (wrong version) |
| 502/503/504 | Proxy/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);
});
| Strategy | Detail |
| Log + drop | Most resilient |
| Send nack | Request resend |
| Close socket | Strict 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 {}
| Class | Use |
WsAuthError | Token rejected |
WsTimeoutError | Request timed out |
WsProtocolError | Server violated contract |
7. Implementing Error Logging
| Field | Reason |
| code/reason | From CloseEvent |
| duration | Connection lifetime |
| retryCount | Reconnect attempts |
| userAgent / netType | Triage |
| lastSendBufferedAmount | Backpressure signal |
8. Implementing Error Recovery
Recovery Flow
- Capture
close code + reason
- Classify: recoverable / auth / fatal
- Refresh credentials if auth error
- Schedule reconnect with backoff
- On open: resubscribe + resync missed messages
9. Handling Buffer Overflow
| Detection | Action |
bufferedAmount > threshold | Pause producers |
| Close 1009 | Reduce message size |
| Memory pressure | Drop low-priority messages |
10. Displaying User-Friendly Errors
| State | UI 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…" |