Skip to content

Errors

Every failed API call throws an SMSFabricError, after the client’s own retries have run out. Webhook verification throws a SignatureVerificationError. Both extend Error, so instanceof works in ESM and CommonJS.

The API answers errors as RFC 9457 problem details. The client copies them onto the error:

Field Type What it holds
status number The HTTP status, or 0 when no response arrived.
code string A stable, machine-readable code such as validation_failed or verify_resend_limited. http_<status> when the body was not JSON. network_error when status is 0.
detail string | undefined A human-readable explanation. Don’t match on it; it can change.
errors Array<{ field, message }> | undefined One entry per invalid field, for 400 validation_failed and a few others.
params Record<string, string | number> | undefined On plan refusals: the values behind detail, such as the plan, the limit and when it resets. See Plan refusals.
requestId string | undefined The request id, from the body or the X-Request-Id header. Quote it when you contact support.
headers Headers | undefined The response headers. undefined for a network error.
retryAfter number | undefined Seconds to wait before trying again, from the Retry-After header (seconds or a date) or the problem’s retryAfter field. Set on 429s such as verify_resend_limited and on some 503s.
cause unknown For a network error, the error fetch threw.
message string SMSFabric <status> <code>: <detail>, for logs.
handle-errors.ts
import { SMSFabric, SMSFabricError } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });
try {
await sms.messages.send({ to: '+2010', body: 'Hello' });
} catch (err) {
if (!(err instanceof SMSFabricError)) throw err;
if (err.code === 'validation_failed') {
for (const e of err.errors ?? []) console.error(`${e.field}: ${e.message}`); // to[0]: must be a valid E.164 phone number
} else {
console.error(err.status, err.code, err.detail, err.requestId);
}
}

Use retryAfter to tell a user when they can ask for another code:

retry-after.ts
import { SMSFabric, SMSFabricError } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });
try {
await sms.verifications.send({ to: '+201001234567' });
} catch (err) {
if (!(err instanceof SMSFabricError) || err.status !== 429) throw err;
const minutes = Math.ceil((err.retryAfter ?? 60) / 60);
console.log(`Too many codes for this number. Try again in ${minutes} min.`); // err.headers.get('retry-after') has the raw value
}

When the request never got an answer (DNS failure, refused connection, TLS error or a timeoutMs timeout), the error has status: 0 and code: 'network_error', and message names the underlying cause, for example Request to SMSFabric failed: fetch failed (connect ECONNREFUSED 127.0.0.1:3000) or Request to SMSFabric failed: timed out after 30000 ms. The original error is on cause.

The full list, with what to do for each, is in Error codes.

Status code What to do
400 validation_failed Fix the fields listed in errors.
401 unauthorized The key or token is missing, wrong, expired or revoked.
403 forbidden The key lacks the scope, or the user’s role lacks the permission.
403 api_key_not_allowed The endpoint needs a user access token. See API keys.
403 tenant_suspended The organization is suspended. Contact support.
404 not_found The id does not exist, or belongs to another organization.
409 idempotency_in_progress A request with the same key is still running. The client retries it.
409 invalid_campaign_state The campaign is not in a state that allows this action. Read it first.
422 idempotency_key_reused The same key was used with a different body. Use a new key.
403 plan_limit_reached, feature_not_in_plan The plan has no room for another one, or doesn’t include the feature. See Plan refusals.
429 rate_limited Too many requests. The client waits for Retry-After and retries.
429 quota_exceeded The plan’s daily or monthly message allowance is used up. Thrown at once, never retried.
429 verify_resend_limited, verify_velocity_exceeded Verify limits. Not retried; show the user when to try again, from retryAfter.
5xx varies A server problem. The client retries; if it persists, contact support with the requestId.

The client already retries 429, 408, 425, 500, 502, 503, 504, 409 idempotency_in_progress and network errors for requests that are safe to repeat. The exception is 429 quota_exceeded: the allowance comes back at the end of the day or month, not after a short wait, so the client throws it on the first answer. When it finally throws:

  • Don’t retry 400, 401, 403, 404 and 422. The same request fails the same way; fix it first.
  • Wait for the reset on quota_exceeded: hold the messages until params.resetsAt.
  • Retry later other 429s and 5xx from a job queue with its own backoff, keeping the same idempotency key for creates.
  • Read before retrying a network_error on a state change that has no idempotency key.
retryable.ts
import { SMSFabricError } from '@smsfabric/sdk';
/** True when the same request may succeed later. */
export function isRetryable(err: unknown): boolean {
if (!(err instanceof SMSFabricError)) return false;
if (err.status === 0) return true;
// A used-up plan allowance comes back only when the day or month resets.
if (err.code === 'quota_exceeded') return false;
return err.status === 429 || err.status >= 500;
}

When a request goes past your plan, the error carries params beside the English detail, so you can word the message yourself or act on the numbers:

code Status params
plan_limit_reached 403 plan, resource (phones, seats, apiKeys, webhooks or recipients), limit
feature_not_in_plan 403 plan, feature (pools, scheduled_sends or csv_export)
quota_exceeded 429 plan, period (day or month), limit, resetsAt (ISO 8601, UTC)
plan-refusal.ts
import { SMSFabric, SMSFabricError } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });
try {
await sms.messages.send({ to: '+201001234567', body: 'Your order 1042 has shipped.' });
} catch (err) {
if (!(err instanceof SMSFabricError)) throw err;
const p = err.params ?? {};
if (err.code === 'quota_exceeded') {
console.error(`The ${p['plan']} plan's ${p['period']} allowance of ${p['limit']} is used up until ${p['resetsAt']}.`);
} else if (err.code === 'plan_limit_reached') {
console.error(`The ${p['plan']} plan allows ${p['limit']} ${p['resource']}.`);
} else if (err.code === 'feature_not_in_plan') {
console.error(`The ${p['plan']} plan does not include ${p['feature']}.`);
} else {
throw err;
}
}

sms.org.plan() returns the same limits and the usage behind them (Account).

Thrown by constructEvent when the SMSFabric-Signature header is missing or malformed, the signature does not match, it is older than the tolerance (300 seconds by default), or the signed body is not a JSON object (the SyntaxError is on cause). Answer 400 and don’t process the body. It needs no client: import constructEvent directly.

signature-error.ts
import { constructEvent, SignatureVerificationError } from '@smsfabric/sdk';
export function parseEvent(rawBody: Buffer, header: string | undefined): { status: number; type?: string } {
try {
const event = constructEvent(rawBody, header, process.env.SMSFABRIC_WEBHOOK_SECRET ?? '');
return { status: 200, type: event.type };
} catch (err) {
if (err instanceof SignatureVerificationError) return { status: 400 };
throw err;
}
}

new SMSFabric() throws a plain Error when it finds no credentials: neither apiKey, nor SMSFABRIC_API_KEY, nor accessToken. Check the environment your process actually runs with.