Skip to main content

Error Handling

aiclientjs throws typed AIError instances with structured error codes.

Catching Errors

import { ai, AIError } from 'aiclientjs';

try {
const res = await ai('Hello');
} catch (err) {
if (err instanceof AIError) {
console.log(err.code); // 'AUTH_ERROR' | 'RATE_LIMIT' | etc.
console.log(err.statusCode); // 401, 429, 500, etc.
console.log(err.provider); // 'openai', 'anthropic', etc.
console.log(err.message); // Human-readable description
}
}

Error Codes

CodeDescriptionCommon Cause
AUTH_ERRORAuthentication failedInvalid or missing API key
RATE_LIMITRate limit exceededToo many requests
PROVIDER_ERRORProvider returned an errorServer error, invalid model, etc.
INVALID_CONFIGBad configurationMissing required options
UNKNOWN_PROVIDERProvider not foundTypo in provider name
SCHEMA_VALIDATIONStructured output failedModel returned invalid JSON
STREAM_ABORTEDStream was cancelledabort() called or signal aborted
NETWORK_ERRORNetwork failureNo internet, DNS failure, etc.
TOOL_EXECUTION_ERRORTool execute threwBug in your tool handler

Handling Specific Errors

try {
const res = await ai('Hello');
} catch (err) {
if (!(err instanceof AIError)) throw err;

switch (err.code) {
case 'AUTH_ERROR':
console.log('Check your API key');
break;
case 'RATE_LIMIT':
console.log('Slow down — retrying in 5s...');
await new Promise(r => setTimeout(r, 5000));
break;
case 'SCHEMA_VALIDATION':
console.log('Model returned bad JSON, try again');
break;
default:
throw err;
}
}

Static Factory Methods

AIError provides named constructors for common errors:

AIError.authentication('openai');
AIError.rateLimit('anthropic');
AIError.providerError('google', 500, 'Internal error');
AIError.invalidConfig('Missing model name');
AIError.unknownProvider('typo-provider');
AIError.schemaValidation('Expected object, got string');
AIError.streamAborted();

These are useful when building custom providers.