WebRTC JS SDK Error Handling
This document provides a comprehensive overview of error handling in the Telnyx WebRTC JS SDK, including when thetelnyx.notification event is triggered, the types of errors that can occur, and how the SDK handles reconnection attempts.
Table of Contents
- WebRTC JS SDK Error Handling
Introduction
The Telnyx WebRTC JS SDK provides robust error handling mechanisms to help developers manage various error scenarios that may occur during the lifecycle of a WebRTC connection. Understanding these error handling mechanisms is crucial for building reliable applications that can gracefully recover from failures.Error Constants Reference
The following table lists all error constants and codes used in the Telnyx WebRTC JS SDK:| ERROR MESSAGE | ERROR CODE | DESCRIPTION |
|---|---|---|
| Token registration error | -32000 | Error during token registration |
| Credential registration error | -32001 | Error during credential registration |
| Codec error | -32002 | Error related to codec operation |
| Gateway registration timeout | -32003 | Gateway registration timed out |
| Gateway registration failed | -32004 | Gateway registration failed |
| Call not found | N/A | The specified call cannot be found |
| User media error | N/A | Browser does not have permission to access media devices |
| Connection timeout | -329990 | Fake verto timeout error code |
SwEvent Error Reference
The SDK exposes every recoverable failure through specificSwEvent constants. Listening to each event provides clear separation between transport issues, session-level failures, and media-layer errors.
Summary Table
| EVENT | TRIGGER | PAYLOAD | RECOMMENDED HANDLING |
|---|---|---|---|
telnyx.error | Session-level failure (registration retry exhausted, server rejects RPC, BYE fails, etc.) | { error: Error | ErrorResponse, sessionId: string } | Surface actionable message, decide whether to retry or prompt the user to re-authenticate |
telnyx.rtc.mediaError | Browser media APIs fail (device enumeration, permission denials, track issues) | Browser DOMException/Error instance | Ask user to grant permissions, suggest device troubleshooting, downgrade to audio-only |
telnyx.rtc.peerConnectionFailureError | ICE restart cannot recover the peer connection (e.g., repeated failed state) | { error: Error, sessionId: string } dispatched with callId as the listener scope | Tear down the affected call, notify the user, optionally auto-redial once connectivity stabilizes |
Handling Details
telnyx.rtc.mediaError
Triggered whenever media-device related promises reject (enumerating devices, opening a microphone/camera, setting tracks). Inspect the DOMException name to differentiate between NotAllowedError (prompt the user to grant permissions), NotFoundError (show “no devices” guidance), and transient issues (allow retries). Pair this with feature detection and fallbacks described in Handle User Media Permissions Gracefully.
telnyx.rtc.peerConnectionFailureError
Raised by the peer connection monitor when an ICE restart still results in a failed state. The event (SwEvent.RtcPeerConnectionFailureError) is scoped to the call id, so listen on the call instance as well as the session if you need global tracking. Recommended handling: immediately hang up the affected call if silent audio is detected. If autoReconnect is enabled (the default), WebRTC JS SDK will reconnect right away.
Call Termination Reasons
The SDK provides detailed information about why a call has ended through the call’scause and causeCode properties. These properties are available when a call reaches the hangup state.
Call Termination Fields
| FIELD | TYPE | DESCRIPTION |
|---|---|---|
cause | string | General cause description (e.g., “CALL_REJECTED”, “USER_BUSY”) |
causeCode | number | Numerical code for the cause (e.g., 21 for CALL_REJECTED) |
sipCode | number | SIP response code (e.g., 403, 404) |
sipReason | string | SIP reason phrase (e.g., “Forbidden”, “Not Found”) |
Common Cause Values
| CAUSE | DESCRIPTION |
|---|---|
NORMAL_CLEARING | Normal call termination |
USER_BUSY | The remote user is busy |
CALL_REJECTED | The call was rejected by the remote party |
UNALLOCATED_NUMBER | The dialed number is invalid or does not exist |
NO_ANSWER | The call was not answered |
PURGE | Call was purged from the system |
Example Usage
The telnyx.notification Event Handler
Thetelnyx.notification event is the primary mechanism for receiving error notifications and call state updates in the JS SDK. This event provides a way for your application to be notified of errors and take appropriate action.
Event Structure
When is telnyx.notification Triggered?
Thetelnyx.notification event is triggered in the following scenarios:
-
Call State Updates: When a call changes state (ringing, active, hangup, etc.)
- Event Type:
callUpdate - Contains:
callobject with current state and termination details
- Event Type:
-
User Media Errors: When the browser cannot access media devices
- Event Type:
userMediaError - Contains:
errorobject with details about the media access failure
- Event Type:
-
Connection State Changes: When the client connection state changes
- Event Type:
vertoClientReady - Indicates the client is ready to make/receive calls
- Event Type:
Example Implementation
Error Types
The SDK encounters different types of errors that require different handling approaches.User Media Errors
User media errors occur when the browser cannot access the user’s microphone or camera. Common Causes:- User denied permission to access media devices
- Media devices are not available or in use by another application
- Browser security restrictions (HTTPS required for media access)
- Invalid audio/video constraints
Call State Errors
Call state errors are indicated through the call’s state transitions and termination reasons. Call States:new: New call has been createdtrying: Attempting to establish the callrequesting: The outbound call is being sent to the serverringing: Incoming call or outbound call is ringinganswering: Attempting to answer an incoming callearly: Receiving media before the call is answeredactive: Call is connected and activeheld: Call is on holdhangup: Call has endeddestroy: Call object is being destroyedpurge: Call has been purged from the system
Connection Errors
Connection errors occur when there are issues with the WebSocket connection to the Telnyx servers. Common Connection Issues:- Network connectivity problems
- Authentication failures
- Server-side issues
- Firewall or proxy blocking WebSocket connections
Socket Connection Close and Socket Connection Error Handling
The Telnyx WebRTC JS SDK forwards those events directly to your application without modification. The WebSocket is used strictly for signaling—media keeps flowing over the underlying WebRTC peer connection—so transient socket interruptions do not require you to drop active calls. The SDK automatically re-establishes signaling when the socket returns, restoring subscriptions and resuming message delivery.Event delivery to TelnyxRTC consumers
telnyx.socket.closeis fired when the underlying WebSocket transitions into theCLOSING/CLOSEDstates and the browser emits aCloseEvent. The SDK does not mutate the event.telnyx.socket.erroris fired on from the WebSocket implementation (for example, TLS handshake issues, DNS failures, or rejected frames). The SDK wraps the error along with the Telnyx session identifier.
autoReconnect is enabled (the default), the SDK clears subscriptions and schedules a reconnect using the configured delay.
telnyx.socket.close payload
Your handler receives the raw CloseEvent. Key fields you can rely on:
event.code- numeric close code set by Cowboy. Common codes include:1000: Normal closure (intentional disconnect or logout).1001: Endpoint is going away (browser has navigated away or lost network).1002: Protocol error (unexpected or malformed frame).1003: Unsupported data (frame contained an unsupported type).1005: No status code present. Browsers surface it when the peer omits a status code entirely or the connection drops unexpectedly.1006: Abnormal closure observed by the browser when the TCP socket drops without a close frame.1011: Internal error raised by the voice proxy.
event.reason- string provided by Cowboy when additional context is available.event.wasClean-truewhen the browser confirms the close handshake completed cleanly.
telnyx.socket.error payload
The SDK provides an object with the signature { error, sessionId }:
error- the originalErrorEvent(or the WebSocket polyfill equivalent) supplied by the browser. WebSocket APIs intentionally keep this opaque; you typically only geterror.typeanderror.message.sessionId- the Telnyx session identifier associated with the current socket.
Monitoring WebSocket ready states
The browser exposes the WebSocketreadyState as an integer (0-3). The SDK mirrors these values through convenience getters on client.connection so you can check the state without touching the underlying socket:
readyState label | Numeric value | SDK getter | Description |
|---|---|---|---|
CONNECTING | 0 | client.connection.connecting | Handshake in progress; no frames exchanged yet. |
OPEN | 1 | client.connection.connected | Socket is open and ready for signaling. |
CLOSING | 2 | client.connection.closing | Close frame has been sent or received; waiting for completion. |
CLOSED | 3 | client.connection.closed | Socket is fully closed. |
client.connection.isAlive is true when the socket is CONNECTING or OPEN, while client.connection.isDead is true during CLOSING or CLOSED.
CloseEvent Reference
The SDK exposes the browser-nativeCloseEvent object so you can inspect the details that originated from the Cowboy proxy or from the browser itself.
code(number) - Close status code described earlier in this section.reason(string) - Optional human-readable message supplied by the server. Cowboy sends concise reasons when available.wasClean(boolean) - Indicates whether both peers completed the close handshake.type(string) - Always"close"for this event, useful when sharing logging infrastructure with other event types.target.url(string) - The WebSocket URL that closed. This helps verify the environment/region the client was connected to.timeStamp(number) - Epoch timestamp (DOMHighResTimeStamp) of when the event fired, which is helpful when correlating with other telemetry.
ws package used in Jest tests) expose the same surface area, though some optional fields (like target.url) may be undefined. Guard your logging to cope with those differences.
Recommended Handling Strategies
- Treat
code === 1000(normal closure) as a controlled shutdown (for example, when the user signs out). If the closure was not user initiated, allow the SDK’s reconnection logic to create a fresh session instead of forcing a call hangup. - For
1001,1005, or1006, surface a transient connectivity message and trigger a retry if your workflow can recover gracefully. - Log and alert on
1002,1003, or any value greater than1011; these usually indicate protocol or payload defects that need developer attention. - Use
telnyx.socket.errorevents for observability: capture thesessionId, timestamp, and user context so failures can be correlated with server-side logs. - Gate privileged actions (placing calls, sending DTMF, subscribing to streams) on
client.connection.connectedto prevent user operations from failing while the socket is reconnecting. - Keep call objects alive while the SDK reconnects; WebRTC media continues despite a signaling outage, and the SDK will reattach once the socket is back.
Code Examples for Common Scenarios
Normal closure (user logout)Reconnection Process
The SDK includes automatic reconnection mechanisms to handle temporary network issues:Automatic Reconnection
- Connection Monitoring: The SDK monitors the WebSocket connection status
- Automatic Retry: When a connection is lost, the SDK attempts to reconnect automatically
- Exponential Backoff: Retry intervals increase progressively to avoid overwhelming the server
- Call Recovery: Active calls may be recovered if the connection is restored quickly. If
keepConnectionAliveOnSocketCloseclient option is enabled, the SDK will maintain call state during brief disconnections.