SDK guide
Errors and retries
How the SDK reports failures as SloppyVoiceError, which requests it retries by itself, and how to handle rate limits, idempotency keys, timeouts and cancellation.
Specification: 03 Client transport, envelopes and errors, 00 Overview, architecture and conventions, 05 Accounts, login, sessions, devices and bots, 11 Messages, attachments, read state and presence, 13 MLS profile, 20 Client behaviour and user experience
Every failure the SDK reports is a SloppyVoiceError: a problem object from a server, a network failure or timeout, or a check the SDK made itself. You decide what to do from its code, what the user sees from its userAction, and you leave the retrying of transient failures to the HTTP client, which already follows the rules of 03 §2.7. This page covers those three parts and the options that change them. For the protocol side, read HTTPS API conventions.
The error classes
A SloppyVoiceError carries an RFC 9457 problem object (03 §10.1, 00 §7.9). Every non-2xx HTTP response, every WebSocket error envelope that answers one of your calls, and every SDK-side failure becomes one. Its members:
| Member | Type | Meaning |
|---|---|---|
code |
string |
The registered code, such as core.rate_limited or channel.not_found, or an sdk.* code. Branch on this. |
status |
number |
The HTTP status. 0 for network failures and SDK-side errors. |
title |
string |
A short summary, plain text. Don't parse it. |
detail |
string | undefined |
Human-readable detail, plain text. |
retryable |
boolean |
Whether the same request may succeed later without any change. |
retryAfterMs |
number | null |
The minimum delay before retrying, from the problem or the Retry-After header; null for no hint. |
userAction |
KnownUserAction | The one-tap fix, with unknown values mapped to none (03 §10.2). |
data |
Record<string, unknown> | undefined |
Code-specific data that the code's owner defines. |
instance |
string | undefined |
urn:uuid:<UUIDv7> of this occurrence, which the server logged. |
problem |
Problem | The problem object as received (only the members 03 §10.1 defines), or as the SDK synthesized it. |
title and detail are never markup: render them as plain text, and keep them out of the main message the user sees, because 03 §10.3 item 4 reserves raw codes and detail for diagnostics views. Put instance in diagnostics and in any "contact the admin" flow so that the operator can find the log entry (03 §10.1 rule 4).
When a server answers 4xx or 5xx without a problem object, typically a proxy or load balancer, the SDK builds the problem the status maps to in 03 §10.3 item 3:
- 401 becomes core.unauthenticated, 404 core.not_found, 413 core.too_large and 425 core.too_early.
- 429 becomes core.rate_limited, with
retryAfterMsfromRetry-Afteror else 5 s. - 502, 503 and 504 become core.unavailable, and other 5xx core.internal; both are retryable.
- Other 4xx becomes a non-retryable core.invalid_request.
Each keeps the HTTP status it came with.
SloppyVoiceNetworkError extends SloppyVoiceError for failures where no HTTP response was read. Its code is sdk.network_error, status is 0, retryable is true and userAction is retry. It adds:
| Member | Type | Meaning |
|---|---|---|
timedOut |
boolean |
The attempt hit the per-attempt timeout rather than failing outright. |
ambiguous |
boolean |
The request may have been processed. true for every failure after the request was handed to fetch, because a client can't tell how far it got (03 §2.7). |
url |
string | undefined |
The requested URL without its query. For a URL outside the server's base URL, only the origin, so capability URLs never reach your logs (03 §3.2 rule 1). |
Checking codes
isSloppyVoiceError narrows an unknown caught value. With a second argument it also checks the code, or one of a list of codes:
import { SloppyVoiceClient, SloppyVoiceNetworkError, botToken, isSloppyVoiceError, type ForbiddenData } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'
const sv = new SloppyVoiceClient({
client: 'my-bot/1.0',
auth: botToken(process.env.SV_BOT_TOKEN ?? ''),
home: 'sloppyvoice.com',
txt: nodeTxtResolver(),
})
const home = await sv.home()
try {
await home.channels.create({ name: 'Raid night', kind: 'voice' })
} catch (err) {
if (err instanceof SloppyVoiceNetworkError) {
// No response was read. The SDK has already retried if the request allowed it.
console.error(err.timedOut ? 'Timed out' : 'Network error', { ambiguous: err.ambiguous })
} else if (isSloppyVoiceError(err, 'core.forbidden')) {
const data = err.data as ForbiddenData | undefined
console.error('Missing permission', data?.permission, 'in', data?.ctx)
} else if (isSloppyVoiceError(err, ['core.conflict', 'core.idempotency_conflict'])) {
console.error('Conflict', err.code)
} else if (isSloppyVoiceError(err)) {
// An unknown code: fall back on the generic members (03 §10.3 item 2).
console.error(err.code, err.status, err.userAction, err.instance)
} else {
throw err
}
}Handle the codes you know the way their owner describes, and treat every other code through its generic members: userAction for what the user sees, retryable and retryAfterMs for retries, status for the class of message. Unknown codes must never crash or block your client (03 §10.3). The full list of codes, with their status, retryable, userAction and data, is in the error reference.
The data types of the core.* codes are exported for casting: InvalidRequestData, ForbiddenData, NotFoundData, MethodNotAllowedData, IdempotencyConflictData, TooLargeData, UnsupportedMediaTypeData, RateLimitedData, UnsupportedVersionData and UnsupportedFeatureData. data comes from the server, so check each member before you use it.
What the user sees
Drive your error UI from userAction, never from the text. Each value has one behaviour in 03 §10.2, and the exact copy of the screens is owned by document 20:
userAction |
What your client does |
|---|---|
none |
A short failure message for the action, from the code if you know it. No button. |
retry |
Offer "Try again". The SDK has already retried automatically where it was allowed. |
wait |
Retry after retryAfterMs. Show a waiting state only if the user has been waiting on this action for more than 2 s. |
sign_in |
The home session is gone and silent recovery failed: show the sign-in screen for the home server, then resume the action. |
enable_encryption |
Show the G1 card, "Turn on encryption", then resume the action. A security.upgrade_required from the home server leads to the blocking screen of 20 §4.4 instead (20 §4.1). |
set_up_device |
Show the G2 card, "Set up encryption on this device", then resume the action. Show G1 instead whenever the account is insecure, because turning on encryption also sets up the device (20 §4.1). |
update_app |
Show the "update required" screen for this server. |
contact_admin |
Say that only the operator can fix this, with the contact details from ServerMetadata if present and instance if present. |
import { isSloppyVoiceError, type SloppyVoiceError } from '@sloppyvoice/sdk'
/** What the UI shows for a failed user action. */
export type ErrorSurface =
| { kind: 'message'; retry: boolean }
| { kind: 'waiting'; retryAfterMs: number }
| { kind: 'sign_in' }
| { kind: 'gate'; card: 'G1' | 'G2' }
| { kind: 'update_required' }
| { kind: 'contact_admin'; instance: string | undefined }
export function surfaceFor(err: unknown): ErrorSurface {
if (!isSloppyVoiceError(err)) return { kind: 'message', retry: false }
return surfaceForAction(err)
}
function surfaceForAction(err: SloppyVoiceError): ErrorSurface {
switch (err.userAction) {
case 'none':
return { kind: 'message', retry: false }
case 'retry':
return { kind: 'message', retry: true }
case 'wait':
return { kind: 'waiting', retryAfterMs: err.retryAfterMs ?? 5000 }
case 'sign_in':
return { kind: 'sign_in' }
case 'enable_encryption':
return { kind: 'gate', card: 'G1' }
case 'set_up_device':
return { kind: 'gate', card: 'G2' }
case 'update_app':
return { kind: 'update_required' }
case 'contact_admin':
return { kind: 'contact_admin', instance: err.instance }
default: {
const unreachable: never = err.userAction
return unreachable
}
}
}The 5 s fallback for wait without a hint is this sample's choice, not a protocol value. The sample also leaves out the two G1 exceptions in the table, which need the error's code, the server and the account's state.
A userAction applies only to the server that sent it, so a remote server can't push your user into another server's screens (03 §10.2, scope rules). The SDK applies rules 1 and 2 for you: on any server other than the account's home server, a sign_in triggers a silent re-creation of the remote session (at most once per 60 s per server), and if the error still reaches you it is reported with userAction: 'wait'. The value the server sent stays in err.problem.userAction. Only the home server's answer leads to sign_in, so you can show the sign-in screen whenever you see it. Rules 3 and 4, which limit update_app, contact_admin and the gate cards to the server and context that sent them, are yours to apply.
Automatic retries
The HTTP client retries a failed request by itself only when every condition of 03 §2.7 holds, with one addition in item 2:
- The request is idempotent:
GET,PUTorDELETE; aPOSTorPATCHsent with anidempotencyKey; or one whose body carries a client-generated ID, such as a messagemid(03 §14.1). Resource methods mark the last kind themselves. - The failure is transient: a network error, a timeout, a problem with
retryable: true(for examplecore.rate_limited,core.unavailable,core.internal, orcore.idempotency_conflictwithreason: "in_progress"), or a bare 502, 503 or 504 without a problem object. The SDK also retries a bare 429, which 03 §10.3 item 3 maps to the retryablecore.rate_limited. - You haven't cancelled through the request's
signal.
The delay before retry n (from 0) is uniformly random in [0, min(30 000, 500 × 2^n)] ms, and never shorter than the retryAfterMs or Retry-After the response gave. The client stops after 5 attempts, the first included, and then throws the last error, so you show its userAction. Every retry sends exactly the same body bytes, which is what the server's idempotency check compares (03 §14.1).
Two cases are retried once whatever the method, even when automatic retries are otherwise off, because the server didn't process the request:
- 401. The client asks the server's TokenProvider to
recover(): a home session refreshes its access token, a remote session gets a fresh HomeAssertion and a new session. If that succeeds the request is sent once more; otherwise the 401 reaches you (03 §3.3). A bot token has nothing to refresh, so a bot sees the 401 at once and should stop and report it. - 425 core.too_early. The request went out in TLS early data; it is resent at once over the completed handshake (03 §2.2 item 4).
A retried DELETE that gets core.not_found or core.gone resolves as a success, because an earlier attempt already deleted it (03 §2.5).
A few endpoints define their own recovery for retryable codes, which 03 §2.7 lets take precedence ("or earlier where the owner says so"). On these the SDK still resends after a network failure, a timeout or a bare 429, 502, 503 or 504, but hands every problem object from the server to you at once, retryable or not:
- MlsApi
groupInfo,groupInfoIfChanged,bootstrapandsubmitCommit, whose callers follow the client group state machine of 13 §16. Back off from a 425 mls.commit_busy exactly as from a 429 (03 §15.2 item 4, 13 §11.4); unlikecore.too_early, the SDK doesn't resend it. - HistoryApi
createShare, where some refusals need a new share with a newshareId. - DmsApi
create, whose retryabledm.*refusals have their own recovery in document 12. A group DM gets an idempotency key, so an unknown outcome is resent; a 1:1 DM creation carries none and is never resent automatically.
Note
03 §10.3 item 3 maps a bare 429 and every bare 5xx to a retryable code, but 03 §2.7 item 1 retries only bare 502, 503 and 504. The SDK retries a bare 429 too, and follows §2.7 for the rest: a bare 500 or other 5xx reaches you with retryable: true without having been retried. Likewise, core.token_expired is registered retryable: true but is only ever retried through the 401 recovery above.
What is never retried
- A non-idempotent request, whatever the failure, apart from the 401 and 425 cases above (03 §2.7 item 2). After a network failure or timeout it may have been processed, so a blind resend is forbidden. You get a
SloppyVoiceNetworkErrorwithambiguous: true; you may ask the user. Give the request an idempotency key (below) and the SDK can retry it safely. - A problem with
retryable: false, such ascore.invalid_request,core.forbiddenorcore.idempotency_conflictwithreason: "mismatch". Sending the same request again would fail the same way. - A request with a streaming body. A
ReadableStreamcan't be replayed, so a rawserver.http.request()with a stream asrawBodyis attempted once. The attachment methods send buffered bytes, so they keep their retries. - Any request after its
signalaborts, including one waiting between attempts. - Problem objects on the MLS, history and DM endpoints above, which go to their own recovery.
The HTTP client doesn't run the longer schedules some owners define, which take precedence over the 5-attempt limit (03 §2.7): the message outbox of 11 §13.4 and the call rejoin schedule of 15 §10.5. The SDK encodes their rules as pure helpers that do no I/O, outboxDecision and outboxRetryDelayMs for the outbox (An outbox) and CallContinuity for rejoining (Continuity and push-to-talk); your client runs their timers and sends the requests.
Rate limits
An over-limit request gets 429 core.rate_limited, with retryAfterMs, data.policy naming the policy that was exceeded, and the Retry-After, RateLimit and RateLimit-Policy headers (03 §15.2). The problem is retryable: true with userAction: "wait", so for an idempotent request the SDK waits at least retryAfterMs and tries again, up to the attempt limit. When the error reaches you:
- Don't send that request again before
retryAfterMshas passed (03 §15.4 item 1). - Show a waiting state only for a user-initiated action delayed by more than 2 s (03 §15.4 item 3).
- Read
data.policy(RateLimitedData) to tell a per-session limit (session) from a per-address one (ip) or an owner's named policy such asbackup.download(03 §15.1).
Servers must allow at least 120 requests per 60 s per session, and 600 is the recommended default (03 §15.3), so a client that hits the limit in normal use is doing too much in the background. Spread background work and slow down before you are refused by reading the advisory RateLimit header (03 §15.4 item 2), which servers SHOULD also send on successful responses (03 §15.2 item 2). parseRateLimit and parseRateLimitPolicy parse the structured-field values; a fetch wrapper sees every response:
import { SloppyVoiceClient, botToken, parseRateLimit } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'
let slowDownUntil = 0
const sv = new SloppyVoiceClient({
client: 'my-bot/1.0',
auth: botToken(process.env.SV_BOT_TOKEN ?? ''),
home: 'sloppyvoice.com',
txt: nodeTxtResolver(),
fetch: async (input, init) => {
const res = await globalThis.fetch(input, init)
for (const limit of parseRateLimit(res.headers.get('RateLimit'))) {
if (limit.remaining !== undefined && limit.remaining < 10 && limit.resetSeconds !== undefined) {
slowDownUntil = Math.max(slowDownUntil, Date.now() + limit.resetSeconds * 1000)
}
}
return res
},
})
/** Background jobs check this before each request. */
export function backgroundMayRun(): boolean {
return Date.now() >= slowDownUntil
}
export { sv }If you build a FetchHttpClient yourself, its onResponse option reports each response's parsed rateLimit, rateLimitPolicy and retryAfterMs as a ResponseInfo instead.
On the event WebSocket an over-limit client message is answered with an error carrying core.rate_limited and retryAfterMs (03 §15.2 item 3). The EventSocket handles that itself: it pauses sending for retryAfterMs (1 s if the error gives none) and sends the message again, so the call that sent it doesn't reject. A server may close the socket with 4029 after 3 such errors within 60 s (03 §7.6), so keep client messages under the limit rather than relying on the resend.
Idempotency keys
Every resource method takes { signal?, idempotencyKey? } as its last argument (RequestOptions). An idempotencyKey is sent as the Idempotency-Key header, makes a POST or PATCH safe to retry, and lets the server answer a repeat with the stored response instead of doing the work twice (03 §14.2). The key is 1 to 64 characters of A-Z a-z 0-9 - . _ ~, optionally in double quotes, which the SDK removes; anything else throws sdk.invalid_argument before the request is sent. On GET the key is still checked, but not sent, because servers ignore it there (03 §14.2 item 1).
The SDK already sends a key, a fresh UUIDv7, where an owner requires or recommends one: ChannelsApi create and upgrade, CommunityApi upgrade, RolesApi create and reorder, BansApi create, the ModerationApi actions (deleteMessages, kick, timeout, serverMute), ReportsApi file and forward, CallsApi join, putMute and deleteMute, and group DM creation. Other POST calls send none unless you pass one; InvitesApi create is one of them.
An automatic retry reuses the key by itself. When your own code retries, after a SloppyVoiceNetworkError or when the user taps "Try again", reuse the same key, because a new key is a new operation and the server would do it twice. Create the key with newIdempotencyKey when the user starts the action, not inside the retry:
import { isSloppyVoiceError, newIdempotencyKey, type Invite, type ServerClient } from '@sloppyvoice/sdk'
/** One "Create invite" action. Every attempt sends the same key, so the server creates at most one invite. */
export function createInviteAction(server: ServerClient) {
const idempotencyKey = newIdempotencyKey()
return async function attempt(): Promise<Invite> {
try {
return await server.invites.create({ maxUses: 10 }, { idempotencyKey })
} catch (err) {
if (isSloppyVoiceError(err, 'core.idempotency_conflict') && err.data?.reason === 'mismatch') {
// The key was used with a different request: a bug in the caller, not a transient failure.
throw new Error('Idempotency key reused for a different request', { cause: err })
}
throw err
}
}
}Servers keep each key for at least 24 h (03 §14.2 item 5). A repeat with the same key and a different request gets 409 core.idempotency_conflict with reason: "mismatch"; a repeat while the first request is still running gets the same code with reason: "in_progress" and retryable: true, which the SDK retries. For a client-generated ID the server also gives a retryAfterMs of at least 500 (03 §14.1 item 6).
Client-generated IDs replace the key where the body carries one. A message's mid is its idempotency key, so MessagesApi send and post don't send Idempotency-Key at all, and a resend with the same mid returns the stored EntryAck (11 §4.6). To resend a message from your outbox, keep its mid:
import { type EntryAck, type ServerClient } from '@sloppyvoice/sdk'
export async function sendWithOutbox(server: ServerClient, ctx: string, text: string): Promise<EntryAck> {
// Store the mid with the outbox item before the first attempt (11 §13.4 rule 3).
const mid = server.messages.newMid()
return server.messages.send(ctx, text, { mid })
}Credential-issuing endpoints ignore Idempotency-Key and never store responses (03 §14.2 item 8), because a stored response would hand the same new token to a replay. The SDK throws sdk.invalid_argument if you pass a key to bot creation or bot token issuing and rotation, so the request isn't mistaken for one that is safe to retry. Their owners say how to recover a lost response: restart the login, or for a bot token list the bot's tokens, revoke the unknown one and create a new one (05 §7.4, 05 §15.4).
Timeouts and cancellation
Each attempt times out after 30 s, the default of 03 §2.3 item 5, except where an endpoint's owner states another bound, such as the 120 s of the server upgrade, which the SDK uses instead. Set timeoutMs on SloppyVoiceClientOptions to change the default for every server. A timeout is reported as a SloppyVoiceNetworkError with timedOut: true and ambiguous: true, and is retried like a network error, so the time one call can take is up to 5 attempts plus the delays between them.
To bound the whole call, or to cancel it when the user leaves the screen, pass an AbortSignal. Aborting stops the request in flight and any retry waiting to start (03 §2.7 item 3). The call then rejects with signal.reason, not with a SloppyVoiceError: an AbortError DOMException for controller.abort(), and a TimeoutError for AbortSignal.timeout(). Check signal.aborted first so that a cancellation isn't shown as a failure:
import { type ChannelList, type ServerClient } from '@sloppyvoice/sdk'
export async function loadChannels(server: ServerClient, screen: AbortSignal): Promise<ChannelList | null> {
// Cancel when the screen closes, and give up after 10 s in total.
const signal = AbortSignal.any([screen, AbortSignal.timeout(10_000)])
try {
return await server.channels.list({ signal })
} catch (err) {
if (signal.aborted) {
if (screen.aborted) return null // The user left: show nothing.
throw new Error('Loading channels took too long', { cause: err })
}
throw err
}
}Aborting a request you already sent doesn't undo it: a POST may still have been processed. Keep its idempotency key or client-generated ID if you may send it again.
Paging iterators take the signal in their request options, the last argument, and stop with the same rejection. SloppyVoiceClient home(), server() and serverFor() accept { signal }, but it only stops your wait: discovery for a server is shared between callers and goes on. A remote session isn't created there either, but silently by the first request that needs it.
SDK codes
Failures the SDK detects itself use codes in the reserved sdk.* area. They never travel on the wire, status is 0, and apart from sdk.network_error they have retryable: false and userAction: "none". SDK_ERROR_CODES lists them:
| Code | Raised when |
|---|---|
sdk.invalid_argument |
You passed a value that breaks a wire grammar or an SDK precondition: a malformed mid, an invalid idempotency key, a path segment of . or .., an Authorization header in headers, a non-https base URL. Nothing was sent. |
sdk.not_implemented |
The SDK doesn't implement this yet, or the runtime lacks something it needs (for example Unicode 16.0.0 for address checks). It never silently succeeds instead. |
sdk.protocol_violation |
A peer sent something the protocol doesn't allow: a success body that isn't JSON, a redirect the rules of 03 §2.3 forbid following, a malformed media frame. |
sdk.verification_failed |
A signature, hash or other cryptographic check failed. Treat the data as untrusted. |
sdk.network_error |
No response was read. Always a SloppyVoiceNetworkError. |
sdk.closed |
The event socket was closed or stopped while calls were still pending, and the server sent no problem to report (03 §5.3). |
sdk.invalid_argument and sdk.protocol_violation usually mean a bug in your code or in the server, so log them with data rather than offering the user a retry.