Skip to main content

Error Handling

Handle errors gracefully in your application.

Error Types

import { 
AgentFishError,
AuthenticationError,
PaymentError,
PaymentLimitError,
InsufficientBalanceError,
} from '@agentfish/sdk';

AgentFishError

Base error class for all AgentFish errors.

try {
await agent.fetch('https://api.example.com/data');
} catch (error) {
if (error instanceof AgentFishError) {
console.log(error.message);
console.log(error.code); // Error code
}
}

AuthenticationError

Thrown when the API key is invalid or expired.

try {
await agent.fetch('https://api.example.com/data');
} catch (error) {
if (error instanceof AuthenticationError) {
console.log('Invalid API key - please check your credentials');
}
}

PaymentError

Thrown when a payment fails to process.

try {
await agent.pay(1.0, 'merchant', 'address');
} catch (error) {
if (error instanceof PaymentError) {
console.log(`Payment failed: ${error.message}`);
console.log(`Signature: ${error.signature}`); // May be undefined
}
}

PaymentLimitError

Thrown when a payment exceeds configured limits.

try {
await agent.fetch('https://expensive-api.com/data');
} catch (error) {
if (error instanceof PaymentLimitError) {
console.log(`Requested: $${error.requested}`);
console.log(`Limit: $${error.limit}`);
console.log(`Limit type: ${error.limitType}`); // 'perTx' or 'daily'
}
}

InsufficientBalanceError

Thrown when the wallet doesn't have enough funds.

try {
await agent.fetch('https://api.example.com/data');
} catch (error) {
if (error instanceof InsufficientBalanceError) {
console.log(`Required: $${error.required} USDC`);
console.log(`Balance: $${error.balance} USDC`);
console.log(`Shortfall: $${error.required - error.balance} USDC`);
}
}

Best Practices

Wrap Critical Operations

async function makeAIRequest(prompt: string) {
try {
const response = await agent.fetchJson<{ reply: string }>(
'https://ai-api.com/chat',
{
method: 'POST',
body: JSON.stringify({ prompt }),
maxPayment: 0.10, // Cap at $0.10
}
);
return response.reply;
} catch (error) {
if (error instanceof InsufficientBalanceError) {
// Prompt user to add funds
throw new Error('Please add funds to continue');
}
if (error instanceof PaymentLimitError) {
// Request exceeds limits
throw new Error('This request is too expensive');
}
// Re-throw unknown errors
throw error;
}
}

Use maxPayment for Safety

Always set maxPayment to prevent unexpected charges:

// Good: Caps payment at $1
const response = await agent.fetch(url, { maxPayment: 1.0 });

// Risky: No limit on payment amount
const response = await agent.fetch(url);

Check Balance Before Operations

const balance = await agent.getBalance();

if (balance.balance < 1.0) {
console.log('Low balance - please add funds');
}

if (balance.dailyRemaining < 0.10) {
console.log('Daily limit almost reached');
}