Error handling
Sometimes things go wrong: a wrong key, no internet, no credits left. When that happens, every SDK method throws a NuRouteError. This happens whenever the answer is not a success (a non-2xx status) or the network fails.
Use a try / catch block to handle it, so your program does not crash.
What a NuRouteError tells you
import { NuRouteClient, NuRouteError } from '@aicp/sdk';
try {
await client.chat.complete({ model: 'auto', messages: [] });
} catch (err) {
if (err instanceof NuRouteError) {
console.error(err.status); // HTTP status code (0 for network errors)
console.error(err.message); // human-readable message
console.error(err.errorType); // error type string
console.error(err.code); // machine-readable code or null
}
}
| Field | Plain meaning |
|---|---|
status | The HTTP status number, like 401 or 429. It is 0 when the network failed |
message | A sentence a person can read |
errorType | A short label for the kind of error |
code | A label for programs, or null |
Common error types
Two different 402 errors
A 402 means "payment needed", and it has two causes: your organization's prepaid credits are used up, or the project's hard-limited monthly budget is spent. errorType tells them apart:
try {
await client.chat.complete({ model: 'auto', messages });
} catch (err) {
if (err instanceof NuRouteError && err.status === 402) {
if (err.errorType === 'insufficient_credits') console.log('Top up your credits on the Billing page.');
if (err.errorType === 'budget_exceeded') console.log("Raise the project's budget, or wait for next month (UTC).");
}
}
Try again when the network fails
A network error is often a short hiccup, so trying again can work. This helper tries up to 3 times, and waits longer each time (0.5 s, then 1 s):
async function withRetry<T>(fn: () => Promise<T>, retries = 3): Promise<T> {
for (let i = 0; i < retries; i++) {
try {
return await fn();
} catch (err) {
if (err instanceof NuRouteError && err.errorType === 'network_error' && i < retries - 1) {
await new Promise(r => setTimeout(r, 2 ** i * 500));
continue;
}
throw err;
}
}
throw new Error('unreachable');
}
const response = await withRetry(() =>
client.chat.complete({ model: 'auto', messages })
);
It retries only on network_error. Other errors, like a wrong key, would fail the same way every time, so they are thrown straight away.