# Error Handling

## Connection Errors

If the connection fails, the WebSocket will trigger an `error` event. Clients should implement a reconnection mechanism.

### Common Connection Issues

1. **403 Forbidden Error**:
   * This usually indicates that the server rejected the connection due to missing or invalid headers
   * **Solution**: Ensure you include a `User-Agent` header and optionally an `Origin` header when connecting
   * Node.js clients using the `ws` library must explicitly set these headers
2. **Connection Timeout**:
   * Check your network connection and firewall settings
   * Verify the WebSocket URL is correct
3. **Unexpected Server Response**:
   * Ensure you're using the correct protocol (`wss://` for secure connections)
   * Verify the server endpoint is accessible

## Message Format Errors

If the message format is incorrect, the server may not respond or return an error. Please ensure:

* JSON format is correct
* All required parameters are provided
* Parameter types are correct (e.g., `chainId` is a number, `instrument` is a string)
* `method` is either `"SUBSCRIBE"` or `"UNSUBSCRIBE"`
* `type` matches one of the supported subscription types

## Reconnection Strategy

When implementing reconnection logic, consider:

1. **Exponential Backoff**: Start with a short delay (e.g., 1 second) and increase it exponentially (2s, 4s, 8s, etc.) up to a maximum delay
2. **Max Retries**: Set a maximum number of reconnection attempts before giving up
3. **Resubscribe**: After reconnecting, resubscribe to all previously active subscriptions
4. **State Management**: Track subscription state to know what to resubscribe to

## Error Response Format

If the server returns an error, it may follow this format:

```json
{
  "id": <number>,
  "error": {
    "code": <number>,
    "message": "<error message>"
  }
}
```

## Best Practices

* Always validate incoming messages before processing
* Implement proper error logging
* Handle network interruptions gracefully
* Test reconnection logic thoroughly
* Monitor connection health using heartbeat mechanism
