Error Handling
The AnvioError class, its error codes, and how tool and runtime failures are surfaced without throwing.
4 min read
Anvio uses one shared error class, AnvioError, defined in packages/core/src/errors/anvio-error.ts. It carries an HTTP-style status code and a stable error code so both the REST layer and the CLI can react consistently.
AnvioError
export type AnvioErrorCode =
| 'VALIDATION_ERROR'
| 'NOT_FOUND'
| 'UNAUTHORIZED'
| 'FORBIDDEN'
| 'CONFLICT'
| 'AGENT_RUNTIME_ERROR'
| 'MODEL_PROVIDER_ERROR'
| 'MEMORY_ERROR'
| 'TOOL_EXECUTION_ERROR'
| 'APPROVAL_REQUIRED'
| 'INTERNAL_ERROR';
export class AnvioError extends Error {
readonly code: AnvioErrorCode;
readonly statusCode: number;
readonly details?: unknown;
constructor(
code: AnvioErrorCode,
message: string,
options?: { statusCode?: number; details?: unknown; cause?: Error },
) { /* ... */ }
}AnvioError extends the native Error and forwards cause, so stack traces and Error.cause chains stay intact through console.error and OpenTelemetry span recording.
Default status codes
Each error code maps to a default HTTP status unless you override it explicitly:
| Code | Default status | Typical origin |
|---|---|---|
VALIDATION_ERROR | 400 | Zod schema parse failure (agent YAML, MCP config, tool arguments) |
UNAUTHORIZED | 401 | Missing/invalid auth token (only relevant when auth.enabled: true) |
FORBIDDEN | 403 | Auth principal lacks permission |
NOT_FOUND | 404 | Unknown agent, session, or dependency ID |
CONFLICT | 409 | Duplicate resource / state conflict |
APPROVAL_REQUIRED | 422 | Tool call needs human approval before it can proceed |
AGENT_RUNTIME_ERROR | 502 | Runtime provider failed (Claude Code, Cursor, Codex, local model loop) |
MODEL_PROVIDER_ERROR | 502 | Model API call failed (rate limit, timeout, auth) |
MEMORY_ERROR | 502 | Memory provider read/write failure |
TOOL_EXECUTION_ERROR | 502 | Built-in tool or MCP tool call failed |
INTERNAL_ERROR | 500 | Unclassified failure |
The 502-class codes (AGENT_RUNTIME_ERROR, MODEL_PROVIDER_ERROR, MEMORY_ERROR, TOOL_EXECUTION_ERROR) are grouped deliberately: they represent an upstream dependency failing, not a bug in the request itself — the same convention a reverse proxy uses for a bad backend response.
Throwing an AnvioError
Real usage from packages/agents/src/task-planner.ts:
import { AnvioError } from '@anvio/core';
if (hasCycle) {
throw new AnvioError('VALIDATION_ERROR', 'Cyclic dependency detected in orchestration plan', {
details: { cycle },
});
}
if (!dependencyExists) {
throw new AnvioError('NOT_FOUND', `Unknown dependency: ${depId}`);
}Guidelines:
- Pick the most specific code available. Don't default to
INTERNAL_ERRORjust because it's shorter to write. - Put structured, machine-readable context in
details, not in the message string. - Pass
{ cause: originalError }when wrapping a caught error, so the original stack is preserved.
Tool and MCP failures: results, not exceptions
Built-in tools and MCP calls do not throw AnvioError for expected failure modes (bad input, unreachable API, disabled tool). Instead they return a typed result object with a status field, so a single failed tool call doesn't crash an agent run mid-loop.
BuiltinToolResult (used throughout packages/tools/src/builtins/index.ts):
interface BuiltinToolResult {
name: string;
output: unknown;
status: 'completed' | 'failed' | 'skipped';
error?: string;
}Pattern repeated for every tool case in the gateway dispatch switch:
try {
const out = await fileRead(ctx.workspaceRoot, path);
return { name: call.name, output: out, status: 'completed' };
} catch (error) {
return {
name: call.name,
output: null,
status: 'failed',
error: error instanceof Error ? error.message : String(error),
};
}status: 'skipped' is used for a distinct case — the tool is disabled in workspace/tools/gateway.yaml, or a required dependency (workspaceRoot, codeExecutor) wasn't provided — versus 'failed', which means the tool ran and errored.
The MCP bridge (packages/integrations/src/mcp-bridge.ts) follows the identical shape with McpToolResult, adding a transport: 'stub' | 'stdio' field so callers can tell a real MCP server response from the built-in stub fallback used when a server is misconfigured.
Runtime fallback: errors as routing signals
packages/runtimes/src/runtime-fallback-chain.ts inspects error messages to decide whether a runtime failure should trigger fallback to the next provider in the chain, rather than failing the whole agent run:
const AUTH_FAILOVER_PATTERN =
/not configured|oauth|authentication|authenticated|login required|unauthorized|401|403|token expired|expired token|invalid token|invalid_api_key|auth.*fail|setup-token|API key shadows|subscription auth|not authenticated|login failed/i;If an error matches this pattern (OAuth expired, 401, "login required", etc.), the fallback executor retries with the next runtime in the configured chain (claude-code → cursor → codex → local). Any other error fails immediately — no silent retries on non-auth errors. See Runtimes & Models overview for the full chain-resolution flow.
Summary: which pattern to use
| Situation | Pattern |
|---|---|
| Invalid input to an API/CLI command, missing resource, needs approval | Throw AnvioError with the matching code |
| Built-in tool call failed | Return BuiltinToolResult with status: 'failed' and error set |
| MCP tool call failed or server disabled | Return McpToolResult with status and error set |
| Runtime provider auth expired mid-run | Let isRuntimeFailoverRetryable() classify it; the fallback chain handles retry |
Last updated on