Skip to main content

Error Handling

Handle errors gracefully in your Sekuire agents.

Error Types

ErrorDescriptionRecoverable
AuthenticationErrorInvalid or expired credentialsYes (refresh)
NetworkErrorConnection failedYes (retry)
RateLimitErrorToo many requestsYes (backoff)
PolicyViolationErrorAction blocked by policyNo
ToolExecutionErrorTool failed to executeDepends
LLMErrorLLM provider errorYes (retry)
TimeoutErrorOperation timed outYes (retry)

Catching Errors

import {
SekuireError,
AuthenticationError,
PolicyViolationError,
RateLimitError,
ToolExecutionError
} from '@sekuire/sdk';

try {
const response = await agent.chat('Do something risky');
} catch (error) {
if (error instanceof PolicyViolationError) {
console.error('Action blocked:', error.policy, error.action);
// Cannot retry - policy blocks this action
} else if (error instanceof RateLimitError) {
console.log('Rate limited, retry after:', error.retryAfter);
await sleep(error.retryAfter);
// Retry the request
} else if (error instanceof AuthenticationError) {
console.error('Auth failed:', error.message);
await sdk.refreshToken();
// Retry the request
} else if (error instanceof ToolExecutionError) {
console.error('Tool failed:', error.toolName, error.message);
// Handle tool-specific error
} else if (error instanceof SekuireError) {
console.error('Sekuire error:', error.code, error.message);
} else {
throw error; // Unknown error
}
}

Retry Strategies

Exponential Backoff

import { withRetry, ExponentialBackoff } from '@sekuire/sdk';

const response = await withRetry(
() => agent.chat('Hello'),
{
strategy: new ExponentialBackoff({
initialDelay: 1000, // 1 second
maxDelay: 30000, // 30 seconds
multiplier: 2,
maxRetries: 5
}),
retryOn: [RateLimitError, NetworkError, TimeoutError]
}
);

Custom Retry Logic

async function chatWithRetry(message: string, maxRetries = 3) {
let lastError: Error;

for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await agent.chat(message);
} catch (error) {
lastError = error;

if (error instanceof PolicyViolationError) {
throw error; // Don't retry policy violations
}

if (attempt < maxRetries) {
const delay = Math.min(1000 * Math.pow(2, attempt), 30000);
console.log(`Attempt ${attempt} failed, retrying in ${delay}ms`);
await sleep(delay);
}
}
}

throw lastError;
}

Error Codes

CodeDescription
AUTH_INVALID_TOKENInstall token is invalid
AUTH_EXPIRED_TOKENToken has expired
AUTH_REVOKEDToken was revoked
POLICY_DENIEDAction denied by policy
POLICY_TOOL_BLOCKEDTool not allowed
RATE_LIMIT_EXCEEDEDToo many requests
AGENT_NOT_FOUNDAgent not in registry
TOOL_NOT_FOUNDTool not registered
TOOL_EXECUTION_FAILEDTool threw an error
LLM_PROVIDER_ERRORLLM API error
NETWORK_ERRORConnection failed
TIMEOUTOperation timed out

Graceful Degradation

Handle partial failures gracefully:

async function processWithFallback(data: string) {
try {
// Try primary agent
return await primaryAgent.chat(`Process: ${data}`);
} catch (error) {
if (error instanceof PolicyViolationError) {
// Try alternative approach
console.log('Primary blocked, trying alternative');
return await fallbackAgent.chat(`Summarize: ${data}`);
}
throw error;
}
}

Logging Errors

import { SekuireError, logger } from '@sekuire/sdk';

try {
await agent.chat(message);
} catch (error) {
if (error instanceof SekuireError) {
logger.error('Agent error', {
code: error.code,
message: error.message,
context: error.context,
stack: error.stack
});

// Report to monitoring
await reportError(error);
}
}

Error Events

Listen for error events on the SDK:

sdk.on('error', (error) => {
console.error('SDK error:', error);
});

sdk.on('auth:expired', () => {
console.log('Session expired, refreshing...');
});

sdk.on('connection:lost', () => {
console.log('Connection lost, reconnecting...');
});

sdk.on('connection:restored', () => {
console.log('Connection restored');
});

Best Practices

  1. Always catch SekuireError - Don't let errors crash your agent
  2. Log errors with context - Include request ID, agent ID, timestamp
  3. Use appropriate retry strategies - Not all errors are retryable
  4. Set timeouts - Don't wait forever for responses
  5. Monitor error rates - Alert on unusual error patterns
  6. Graceful shutdown - Handle SIGTERM/SIGINT properly
// Graceful shutdown
process.on('SIGTERM', async () => {
console.log('Shutting down gracefully...');
await sdk.shutdown();
process.exit(0);
});

Next Steps