Skip to main content

Error Handling

The SDK provides structured error handling with the CyberPodError class.

CyberPodError

All API errors are thrown as CyberPodError instances:

import { CyberPodError } from "@cpod/sdk";

try {
await someApiCall();
} catch (error) {
if (error instanceof CyberPodError) {
console.error(`Status: ${error.status}`);
console.error(`Message: ${error.message}`);
console.error(`Details: ${error.details}`);
}
}

Common Error Codes

StatusMeaningHow to Handle
400Bad RequestCheck your request parameters
401UnauthorizedRe-authenticate or refresh token
403ForbiddenUser lacks permission
404Not FoundResource doesn't exist
429Rate LimitedWait and retry with backoff
500Server ErrorRetry or contact support

Handling Specific Errors

import { authenticateUser, CyberPodError } from "@cpod/sdk";

try {
await authenticateUser({ username, password });
} catch (error) {
if (!(error instanceof CyberPodError)) throw error;

switch (error.status) {
case 401:
showError("Invalid username or password");
break;
case 429:
showError("Too many attempts. Please wait.");
break;
case 503:
showError("Service unavailable. Try again later.");
break;
default:
showError(`Error: ${error.message}`);
}
}

Retry Logic

For transient errors, implement retry logic:

import { CyberPodError } from "@cpod/sdk";

async function withRetry<T>(
fn: () => Promise<T>,
maxRetries = 3
): Promise<T> {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
if (!(error instanceof CyberPodError)) throw error;

// Only retry on server errors or rate limits
if (error.status < 500 && error.status !== 429) throw error;

// Exponential backoff
const delay = Math.pow(2, i) * 1000;
await new Promise(r => setTimeout(r, delay));
}
}
throw new Error("Max retries exceeded");
}

// Usage
const user = await withRetry(() => getUser());

SDK Initialization Errors

If you call functions before initializing the SDK:

import { getUser, setBaseUrl } from "@cpod/sdk";

// This will throw!
try {
await getUser();
} catch (error) {
// Error: "SDK not initialized. Call setBaseUrl() first."
}

// Fix: Initialize first
setBaseUrl("https://api.cyberpod.ai");
await getUser(); // Now it works

Network Errors

Network errors (offline, timeout) are thrown as regular Error:

try {
await someApiCall();
} catch (error) {
if (error instanceof CyberPodError) {
// API error - has status code
} else if (error instanceof Error) {
// Network error - no status
if (error.message.includes("fetch")) {
showError("Network error. Check your connection.");
}
}
}

TypeScript Error Types

import { CyberPodError } from "@cpod/sdk";

// The error class
class CyberPodError extends Error {
status: number; // HTTP status code
message: string; // Error message
details?: unknown; // Additional error details
}