Errors and reliability
Handle failed requests, understand automatic retries and set safe timeout and replay policies.
Catch errors where you make a request so your application can decide what to report or recover from. Import SDK error classes from @nirmos/sdk and use instanceof to distinguish them.
Handle a failed request
This example handles cancellation separately and records diagnostic identifiers for HTTP failures. It rethrows other failures so the calling application can decide what to do next.
import { APIError, NirmosError, RequestAbortedError, TimeoutError } from "@nirmos/sdk";
try {
await nirmos.models.list({ capability: "chat" }, { timeoutMs: 10_000 });
} catch (error) {
if (error instanceof RequestAbortedError) {
// The caller cancelled or its AbortSignal deadline expired.
console.log("Request cancelled");
} else {
if (error instanceof TimeoutError) {
console.error("Request exceeded its timeout:", error.timeoutMs);
} else if (error instanceof APIError) {
// HTTP failures can include identifiers useful for troubleshooting.
console.error({
status: error.status,
code: error.code,
requestId: error.requestId,
traceId: error.traceId,
});
} else if (error instanceof NirmosError) {
console.error(error.code, error.message);
}
throw error; // Let the application's error boundary or job handler respond.
}
}HTTP errors extend APIError; SDK errors extend NirmosError. Unknown JavaScript errors can still escape, including errors thrown by your own callbacks.
Respond to common failures
| Failure | Error class | Next step |
|---|---|---|
| Invalid or expired key (401) | AuthenticationError | Check or replace the configured key |
| Missing access (403) | PermissionDeniedError | Check the key's organization and permissions |
| Invalid input (400/422) | ValidationError | Correct the request before trying again |
| Rate limit (429) | RateLimitError | Respect retryAfterMs when present; check quota if failures continue |
| SDK timeout | TimeoutError | Review the timeout and operation status before replaying a mutation |
| Caller cancellation | RequestAbortedError | Stop the operation or handle the caller's deadline |
| Connection failure | NetworkError | Check connectivity and API URLs; browser CORS failures can appear here |
Log the status, error code and available request or trace IDs for support. Avoid logging credentials or full request content. Validate the shape of APIError.details before reading it because its type is unknown.
Automatic retries
The default maxRetries: 2 allows up to three attempts: the first request and two retries. Automatic retries apply to GET requests, or requests with idempotencyKey, for HTTP 408, 429 and 500+ responses and initial Fetch network failures.
Timeouts, caller cancellations and failures while reading a successful response body are not retried. A stream never reconnects or replays automatically after consumption begins.
Set maxRetries on the client or override it for one request:
// Make a single attempt when the caller needs to decide whether to retry.
const page = await nirmos.models.list({}, { maxRetries: 0 });
console.log(page.items.length);SDK retries are separate from runtime or provider retries. An error's retryable field describes the HTTP failure; it does not prove the SDK retried the request.
Set a total deadline
The default SDK timeout is 60 seconds per attempt, including response-body reading. Multiple attempts and retry waits can exceed that duration. Use an AbortSignal to set a deadline for the entire call:
const page = await nirmos.models.list({}, {
timeoutMs: 10_000, // Limit each attempt, including body reading.
maxRetries: 2, // Allow eligible retries within the total deadline.
signal: AbortSignal.timeout(15_000), // Cancel the whole call after 15 seconds.
});
console.log(page.items.length);timeoutMs: 0 disables the SDK timeout. An SDK timer produces TimeoutError; an aborted caller signal produces RequestAbortedError. Cancellation does not establish whether the server completed a mutation.
Replay mutations safely
Most writes and AI generations do not retry automatically. Only supply idempotencyKey when the endpoint supports deduplication; the header alone cannot prevent duplicate work.
Memory ingestion, manual Memory insertion and evaluation run creation support replay keys. For example:
// Persist this key with the input; reuse it only when retrying the same operation.
const replayKey = "customer_123-preference-v1";
const result = await nirmos.memory.items.create({
memorySpaceId: "space-id", // Replace with your Memory space ID.
content: "Customer prefers email.",
type: "preference",
}, {
idempotencyKey: replayKey,
maxRetries: 2, // Safe here because this operation supports server deduplication.
});
console.log("Replayed:", result.replayed);
console.log("Memory run:", result.memoryRunId);Use a new key for a new logical operation. Evaluation run creation returns the existing organization-scoped run when its key is reused. Check the feature guide before enabling retries for other mutations.
Catch errors during streaming
Keep both stream creation and iteration inside the try block. A request can succeed initially and fail while your application reads events.
import { NirmosError } from "@nirmos/sdk";
try {
const stream = await nirmos.gateway.chat.stream({
model: "<provider-slug>/<model-slug>", // Use a configured chat model.
messages: [{ role: "user", content: "Explain an AI gateway in one sentence." }],
});
// Errors can occur here too, after the server has sent response headers.
for await (const event of stream) {
if (event.type === "content.delta") console.log(event.delta ?? "");
}
} catch (error) {
if (error instanceof NirmosError) console.error(error.code, error.message);
throw error; // Decide how to handle partial output in the calling application.
}The SDK does not automatically replay partial streams. See streaming for consuming events and retrieving the final completion.