> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch16-model-providers-and-failover/16.4-failover-error-handling.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 16.4 Failover Error Handling

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~400,000 tokens, Output \~32,000 tokens (Chapter total) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

The core question of failover is: what kind of errors should trigger fallback? What kind of errors should be reported directly to the user? OpenClaw uses the `FailoverError` type and a set of error classification systems to precisely control the conditions that trigger failover.

## 16.4.1 Error Classification (`src/agents/failover-error.ts`)

### FailoverError Class

`FailoverError` is a custom error class that carries all the context information needed for failover:

```typescript
// src/agents/failover-error.ts
export class FailoverError extends Error {
  readonly reason: FailoverReason;    // Failure reason classification
  readonly provider?: string;         // Provider identifier
  readonly model?: string;            // Model identifier
  readonly profileId?: string;        // Auth Profile ID
  readonly status?: number;           // HTTP status code
  readonly code?: string;             // Error code

  constructor(message: string, params: {
    reason: FailoverReason;
    provider?: string;
    model?: string;
    profileId?: string;
    status?: number;
    code?: string;
    cause?: unknown;
  }) {
    super(message, { cause: params.cause });
    this.name = "FailoverError";
    // ... assignments
  }
}
```

The `FailoverReason` enum lists all possible failure reasons:

| reason       | Meaning                            | Typical HTTP Status Code |
| ------------ | ---------------------------------- | ------------------------ |
| `billing`    | Billing error (insufficient quota) | 402                      |
| `rate_limit` | Rate limiting                      | 429                      |
| `auth`       | Authentication failure             | 401 / 403                |
| `timeout`    | Request timeout                    | 408                      |
| `format`     | Request format error               | 400                      |
| `unknown`    | Unknown error                      | —                        |

### Error to Failover Reason Mapping

The `resolveFailoverReasonFromError` function is responsible for mapping any error object to a `FailoverReason`:

```typescript
// src/agents/failover-error.ts
export function resolveFailoverReasonFromError(err: unknown): FailoverReason | null {
  // 1. If already a FailoverError, use its reason directly
  if (isFailoverError(err)) return err.reason;

  // 2. Classify by HTTP status code
  const status = getStatusCode(err);
  if (status === 402) return "billing";
  if (status === 429) return "rate_limit";
  if (status === 401 || status === 403) return "auth";
  if (status === 408) return "timeout";

  // 3. Classify by error code (Node.js network errors)
  const code = getErrorCode(err);
  if (["ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNRESET", "ECONNABORTED"].includes(code)) {
    return "timeout";
  }

  // 4. Classify by error message text
  if (isTimeoutError(err)) return "timeout";
  return classifyFailoverReason(getErrorMessage(err));
}
```

The priority of classification logic is: already marked > HTTP status code > network error code > error message text. This ensures that errors from different SDKs with inconsistent formats can still be correctly classified.

### Timeout Detection

Timeout error detection is particularly complex because timeout errors manifest differently across environments and SDKs:

```typescript
// src/agents/failover-error.ts
const TIMEOUT_HINT_RE = /timeout|timed out|deadline exceeded|context deadline exceeded/i;
const ABORT_TIMEOUT_RE = /request was aborted|request aborted/i;

export function isTimeoutError(err: unknown): boolean {
  // Method 1: Error name is "TimeoutError"
  if (getErrorName(err) === "TimeoutError") return true;

  // Method 2: Error message contains timeout keywords
  if (TIMEOUT_HINT_RE.test(getErrorMessage(err))) return true;

  // Method 3: AbortError + timeout-related message (distinguish user-initiated cancellation from timeout-caused cancellation)
  if (getErrorName(err) === "AbortError") {
    if (ABORT_TIMEOUT_RE.test(getErrorMessage(err))) return true;
    // Also check cause and reason fields
    if (hasTimeoutHint(err.cause) || hasTimeoutHint(err.reason)) return true;
  }

  return false;
}
```

The distinction between timeout and AbortError is critical — an AbortError produced by user-initiated `/stop` should not trigger failover, while an AbortError caused by timeout (such as some HTTP libraries representing timeout as abort) should trigger failover.

### Error Coercion

Regular errors can be "promoted" to `FailoverError`:

```typescript
// src/agents/failover-error.ts
export function coerceToFailoverError(
  err: unknown,
  context?: { provider?: string; model?: string },
): FailoverError | null {
  if (isFailoverError(err)) return err;

  const reason = resolveFailoverReasonFromError(err);
  if (!reason) return null;  // Unclassifiable errors cannot be converted

  return new FailoverError(getErrorMessage(err), {
    reason,
    provider: context?.provider,
    model: context?.model,
    status: getStatusCode(err) ?? resolveFailoverStatus(reason),
    code: getErrorCode(err),
    cause: err,
  });
}
```

If a regular error can be classified as some failure reason, it will be wrapped as a `FailoverError` and enter the failover flow. If it cannot be classified (returns `null`), it means this is an unrecoverable error (such as a configuration error) and should be thrown immediately.

## 16.4.2 Detection and Handling of Authentication Errors, Billing Errors, and Context Overflow Errors

In addition to generic error classification, OpenClaw implements specialized detection and recovery strategies for several specific error types.

### Authentication Errors

Authentication errors typically occur when an API Key is invalid, a Token has expired, or permissions are insufficient. In `runEmbeddedPiAgent`, authentication errors trigger Auth Profile rotation:

```typescript
// Detect authentication error
const authFailure = isAuthAssistantError(lastAssistant);
if (authFailure) {
  await markAuthProfileFailure({ store: authStore, profileId: lastProfileId, reason: "auth" });
  if (await advanceAuthProfile()) continue;  // Switch to next Profile
}
```

### Billing Errors

Billing errors (HTTP 402) mean the user's quota is exhausted. OpenClaw has special handling for billing errors:

1. Mark the Profile to enter a long cooldown period (billing errors have longer backoff time)
2. Attempt to switch to other Profiles (which may have different billing accounts)
3. If all Profiles are billing errors, attempt to fall back to other models
4. Finally, display a dedicated billing error message to the user

### Context Overflow Errors

Context overflow occurs when the conversation history exceeds the model's context window. The recovery strategy for this error is to automatically compact the session history:

```typescript
// src/agents/pi-embedded-runner/run.ts (simplified)
if (isContextOverflowError(errorText)) {
  if (overflowCompactionAttempts < MAX_OVERFLOW_COMPACTION_ATTEMPTS) {  // Max 3 times
    overflowCompactionAttempts++;
    const compactResult = await compactEmbeddedPiSessionDirect({ ... });
    if (compactResult.compacted) {
      continue;  // Compaction successful, retry
    }
  }
  // Compaction failed or max attempts reached
  return { payloads: [{ text: "Context overflow: prompt too large...", isError: true }] };
}
```

Automatic compaction releases Token space by summarizing the early parts of the conversation history. If three consecutive compaction attempts fail to resolve the overflow (possibly because a single message itself exceeds the context window), the error is reported to the user.

### Message Role Order Error

Some LLM APIs require message roles to strictly alternate (user → assistant → user → ...). If consecutive messages of the same role appear in the history, it causes a role order error:

```typescript
if (/incorrect role information|roles must alternate/i.test(errorText)) {
  return {
    payloads: [{
      text: "Message ordering conflict - please try again. " +
            "If this persists, use /new to start a fresh session.",
      isError: true,
    }],
  };
}
```

Role order errors do not trigger failover (because switching to another model will fail the same way) but directly prompt the user to retry or start a new session.

### Image Size Error

When a user sends an image that exceeds the model's limit:

```typescript
const imageSizeError = parseImageSizeError(errorText);
if (imageSizeError) {
  return {
    payloads: [{
      text: `Image too large for the model (max ${imageSizeError.maxMb}MB). ` +
            "Please compress or resize the image and try again.",
      isError: true,
    }],
  };
}
```

Image size errors also do not trigger failover — the user needs to compress the image and resend it.

## 16.4.3 Failover Logging and User-Visible Error Messages

### Failover Logging

Each failover attempt is logged, including:

* The provider and model attempted
* Error message and classification reason
* HTTP status code and error code

```typescript
// src/agents/model-fallback.ts (onError callback)
await params.onError?.({
  provider: candidate.provider,
  model: candidate.model,
  error: normalized,
  attempt: i + 1,
  total: candidates.length,
});
```

### Error Description

The `describeFailoverError` function converts any error object into a structured error description:

```typescript
// src/agents/failover-error.ts
export function describeFailoverError(err: unknown): {
  message: string;
  reason?: FailoverReason;
  status?: number;
  code?: string;
} {
  if (isFailoverError(err)) {
    return { message: err.message, reason: err.reason, status: err.status, code: err.code };
  }
  return {
    message: getErrorMessage(err) || String(err),
    reason: resolveFailoverReasonFromError(err) ?? undefined,
    status: getStatusCode(err),
    code: getErrorCode(err),
  };
}
```

### Error Summary When All Fail

When all candidate models fail, the system aggregates error information from all attempts:

```typescript
// src/agents/model-fallback.ts
const summary = attempts
  .map((attempt) =>
    `${attempt.provider}/${attempt.model}: ${attempt.error}` +
    `${attempt.reason ? ` (${attempt.reason})` : ""}`
  )
  .join(" | ");
throw new Error(`All models failed (${attempts.length}): ${summary}`);
```

For example, a typical all-failed error message might be:

```
All models failed (3): 
  anthropic/claude-sonnet-4-20250514: Rate limit exceeded (rate_limit) | 
  openai/gpt-4o: Authentication failed (auth) | 
  google/gemini-2.5-pro: Request timeout (timeout)
```

This summary message clearly shows the failure reason for each candidate model, helping users or administrators quickly locate the problem.

### User-Visible Error Messages

Error messages for users are carefully designed to avoid exposing internal details:

| Error Type           | User-Visible Message                                                                                     |
| -------------------- | -------------------------------------------------------------------------------------------------------- |
| Context Overflow     | "Context overflow: prompt too large for the model. Try again with less input or a larger-context model." |
| Role Order Conflict  | "Message ordering conflict - please try again. If this persists, use /new to start a fresh session."     |
| Image Too Large      | "Image too large for the model (max NMB). Please compress or resize the image and try again."            |
| Billing Error        | Dedicated `BILLING_ERROR_USER_MESSAGE` constant                                                          |
| Generic Timeout      | "LLM request timed out."                                                                                 |
| Generic Auth Failure | "LLM request unauthorized."                                                                              |
| Generic Rate Limit   | "LLM request rate limited."                                                                              |

All user-visible error messages are accompanied by **actionable suggestions** — telling users what they can do next, rather than just reporting the problem.

***

## Section Summary

1. **`FailoverError`** is the core type of the failover system, carrying complete context including failure reason (`reason`), provider, model, HTTP status code, etc.
2. **Error classification** follows a four-level priority: already marked → HTTP status code → network error code → error message text, ensuring errors from different SDKs are correctly classified.
3. **Distinguishing timeout from AbortError** is key — user-initiated cancellation does not trigger fallback, timeout-caused abort triggers fallback.
4. **Specific error types** (authentication, billing, context overflow, role order, image size) each have specialized detection and recovery strategies that cannot be generalized.
5. **Error aggregation** when all fail shows the complete failure chain, and user-visible error messages include actionable suggestions.

***

> ### 🔬 Going Deeper: 16.5 Source Deep Dive
>
> That's the end of the chapter's main text. If you're going to **modify this code**, or reproduce it in your own project, read on: [**16.5 Source Deep Dive: Auth Profile Rotation, Cooldown, and Degradation**](https://www.openclawbook.xyz/en/ch16-model-providers-and-failover/16.5-source-deep-dive-auth-profile-rotation.md) traces the real implementation line by line along with the issues behind it, at a noticeably higher information density.
>
> **The main text is for understanding structure; the deep dive is for understanding trade-offs.**
