# Send API Error Handling to your agent
Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.
## Fast path
- Download the package from Yavira.
- Extract it into a folder your agent can access.
- Paste one of the prompts below and point your agent at the extracted folder.
## Suggested prompts
### New install

```text
I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete.
```
### Upgrade existing

```text
I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run.
```
## Machine-readable fields
```json
{
  "schemaVersion": "1.0",
  "item": {
    "slug": "api-error-handling",
    "name": "API Error Handling",
    "source": "tencent",
    "type": "skill",
    "category": "开发工具",
    "sourceUrl": "https://clawhub.ai/wpank/api-error-handling",
    "canonicalUrl": "https://clawhub.ai/wpank/api-error-handling",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadUrl": "/downloads/api-error-handling",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=api-error-handling",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "packageFormat": "ZIP package",
    "primaryDoc": "SKILL.md",
    "includedAssets": [
      "README.md",
      "SKILL.md"
    ],
    "downloadMode": "redirect",
    "sourceHealth": {
      "source": "tencent",
      "slug": "api-error-handling",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-04-29T05:54:27.425Z",
      "expiresAt": "2026-05-06T05:54:27.425Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=api-error-handling",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=api-error-handling",
        "contentDisposition": "attachment; filename=\"api-error-handling-1.0.0.zip\"",
        "redirectLocation": null,
        "bodySnippet": null,
        "slug": "api-error-handling"
      },
      "scope": "item",
      "summary": "Item download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this item.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/api-error-handling"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    }
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/api-error-handling",
    "downloadUrl": "https://openagent3.xyz/downloads/api-error-handling",
    "agentUrl": "https://openagent3.xyz/skills/api-error-handling/agent",
    "manifestUrl": "https://openagent3.xyz/skills/api-error-handling/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/api-error-handling/agent.md"
  }
}
```
## Documentation

### Error Handling Patterns

Ship resilient software. Handle errors at boundaries, fail fast and loud, never swallow exceptions silently.

### Error Handling Philosophy

PrincipleDescriptionFail FastDetect errors early — validate inputs at the boundary, not deep in business logicFail LoudErrors must be visible — log them, surface them, alert on themHandle at BoundariesCatch and translate errors at layer boundaries (controller, middleware, gateway)Let It CrashFor unrecoverable state, crash and restart (Erlang/OTP philosophy)Be SpecificCatch specific error types, never bare catch or exceptProvide ContextEvery error carries enough context to diagnose without reproducing

### Error Types

Operational errors — network timeouts, invalid user input, file not found, DB connection lost. Handle gracefully.

Programmer errors — TypeError, null dereference, assertion failures. Fix the code — don't catch and suppress.

// Operational — handle gracefully
try {
  const data = await fetch('/api/users');
} catch (err) {
  if (err.code === 'ECONNREFUSED') return fallbackData;
  throw err; // re-throw unexpected errors
}

// Programmer — let it crash, fix the bug
const user = null;
user.name; // TypeError — don't try/catch this

### Language Patterns

LanguageMechanismAnti-PatternJavaScripttry/catch, Promise.catch, Error subclasses.catch(() => {}) swallowing errorsPythonExceptions, context managers (with)Bare except: catching everythingGoerror returns, errors.Is/As, fmt.Errorf wrapping_ = riskyFunction() ignoring errorRustResult<T, E>, Option<T>, ? operator.unwrap() in production code

### JavaScript — Error Subclasses

class AppError extends Error {
  constructor(message, code, statusCode, details = {}) {
    super(message);
    this.name = this.constructor.name;
    this.code = code;
    this.statusCode = statusCode;
    this.details = details;
    this.isOperational = true;
  }
}

class NotFoundError extends AppError {
  constructor(resource, id) {
    super(\`${resource} not found\`, 'NOT_FOUND', 404, { resource, id });
  }
}

class ValidationError extends AppError {
  constructor(errors) {
    super('Validation failed', 'VALIDATION_ERROR', 422, { errors });
  }
}

### Go — Error Wrapping

func GetUser(id string) (*User, error) {
    row := db.QueryRow("SELECT * FROM users WHERE id = $1", id)
    var user User
    if err := row.Scan(&user.ID, &user.Name); err != nil {
        if errors.Is(err, sql.ErrNoRows) {
            return nil, fmt.Errorf("user %s: %w", id, ErrNotFound)
        }
        return nil, fmt.Errorf("querying user %s: %w", id, err)
    }
    return &user, nil
}

### Express Error Middleware

app.use((err, req, res, next) => {
  const statusCode = err.statusCode || 500;
  const response = {
    error: {
      code: err.code || 'INTERNAL_ERROR',
      message: err.isOperational ? err.message : 'Something went wrong',
      ...(process.env.NODE_ENV === 'development' && { stack: err.stack }),
      requestId: req.id,
    },
  };

  logger.error('Request failed', {
    err, requestId: req.id, method: req.method, path: req.path,
  });

  res.status(statusCode).json(response);
});

### React Error Boundary

import { ErrorBoundary } from 'react-error-boundary';

function ErrorFallback({ error, resetErrorBoundary }) {
  return (
    <div role="alert">
      <h2>Something went wrong</h2>
      <pre>{error.message}</pre>
      <button onClick={resetErrorBoundary}>Try again</button>
    </div>
  );
}

<ErrorBoundary FallbackComponent={ErrorFallback} onReset={() => queryClient.clear()}>
  <App />
</ErrorBoundary>

### Retry Patterns

PatternWhen to UseConfigExponential BackoffTransient failures (network, 503)Base 1s, max 30s, factor 2xBackoff + JitterMultiple clients retryingRandom ±30% on each delayCircuit BreakerDownstream service failing repeatedlyOpen after 5 failures, half-open after 30sBulkheadIsolate failures to prevent cascadeLimit concurrent calls per serviceTimeoutPrevent indefinite hangsConnect 5s, read 30s, total 60s

### Exponential Backoff with Jitter

async function withRetry(fn, { maxRetries = 3, baseDelay = 1000, maxDelay = 30000 } = {}) {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (err) {
      if (attempt === maxRetries || !isRetryable(err)) throw err;
      const delay = Math.min(baseDelay * 2 ** attempt, maxDelay);
      const jitter = delay * (0.7 + Math.random() * 0.6);
      await new Promise((r) => setTimeout(r, jitter));
    }
  }
}

function isRetryable(err) {
  return [408, 429, 500, 502, 503, 504].includes(err.statusCode) || err.code === 'ECONNRESET';
}

### Circuit Breaker

class CircuitBreaker {
  constructor({ threshold = 5, resetTimeout = 30000 } = {}) {
    this.state = 'CLOSED';       // CLOSED → OPEN → HALF_OPEN → CLOSED
    this.failureCount = 0;
    this.threshold = threshold;
    this.resetTimeout = resetTimeout;
    this.nextAttempt = 0;
  }

  async call(fn) {
    if (this.state === 'OPEN') {
      if (Date.now() < this.nextAttempt) throw new Error('Circuit is OPEN');
      this.state = 'HALF_OPEN';
    }
    try {
      const result = await fn();
      this.onSuccess();
      return result;
    } catch (err) {
      this.onFailure();
      throw err;
    }
  }

  onSuccess() { this.failureCount = 0; this.state = 'CLOSED'; }
  onFailure() {
    this.failureCount++;
    if (this.failureCount >= this.threshold) {
      this.state = 'OPEN';
      this.nextAttempt = Date.now() + this.resetTimeout;
    }
  }
}

### HTTP Error Responses

StatusNameWhen to Use400Bad RequestMalformed syntax, invalid JSON401UnauthorizedMissing or invalid authentication403ForbiddenAuthenticated but insufficient permissions404Not FoundResource does not exist409ConflictRequest conflicts with current state422Unprocessable EntityValid syntax but semantic errors429Too Many RequestsRate limit exceeded (include Retry-After)500Internal Server ErrorUnexpected server failure502Bad GatewayUpstream returned invalid response503Service UnavailableTemporarily overloaded or maintenance

### Standard Error Envelope

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "The request body contains invalid fields.",
    "details": [
      { "field": "email", "message": "Must be a valid email address" }
    ],
    "requestId": "req_abc123xyz"
  }
}

### Graceful Degradation

StrategyExampleFallback valuesShow cached avatar when image service is downFeature flagsDisable unstable recommendation engineCached responsesServe stale data with X-Cache: STALE headerPartial responseReturn available data with warnings array

async function getProductPage(productId) {
  const product = await productService.get(productId); // critical — propagate errors

  const [reviews, recommendations] = await Promise.allSettled([
    reviewService.getForProduct(productId),
    recommendationService.getForProduct(productId),
  ]);

  return {
    product,
    reviews: reviews.status === 'fulfilled' ? reviews.value : [],
    recommendations: recommendations.status === 'fulfilled' ? recommendations.value : [],
    warnings: [reviews, recommendations]
      .filter((r) => r.status === 'rejected')
      .map((r) => ({ service: 'degraded', reason: r.reason.message })),
  };
}

### Logging & Monitoring

PracticeImplementationStructured loggingJSON: level, message, error, requestId, userId, timestampError trackingSentry, Datadog, Bugsnag — automatic capture with source mapsAlert thresholdsError rate > 1%, P99 latency > 2s, 5xx spikeCorrelation IDsPass requestId through all service callsLog levelserror = needs attention, warn = degraded, info = normal, debug = dev

### Anti-Patterns

Anti-PatternFixSwallowing errors catch (e) {}Log and re-throw, or handle explicitlyGeneric catch-all at every levelCatch specific types, let unexpected errors bubbleError as control flowUse conditionals, return values, or option typesStringly-typed errors throw "wrong"Throw Error objects with codes and contextLogging and throwingLog at the boundary only, or wrap and re-throwCatch-and-return-nullReturn Result type, throw, or return error objectIgnoring Promise rejectionsAlways await or attach .catch()Exposing internalsSanitize responses; log details server-side only

### NEVER Do

NEVER swallow errors silently — catch (e) {} hides bugs and causes silent data corruption
NEVER expose stack traces, SQL errors, or file paths in API responses — log details server-side only
NEVER use string throws — throw 'error' has no stack trace, no type, no context
NEVER catch and return null without explanation — callers have no idea why the operation failed
NEVER ignore unhandled Promise rejections — always await or attach .catch()
NEVER cache error responses — 5xx and transient errors must not be cached and re-served
NEVER use exceptions for normal control flow — exceptions are for exceptional conditions
NEVER return generic "Something went wrong" without logging the real error — always log the full error server-side with request context
## Trust
- Source: tencent
- Verification: Indexed source record
- Publisher: wpank
- Version: 1.0.0
## Source health
- Status: healthy
- Item download looks usable.
- Yavira can redirect you to the upstream package for this item.
- Health scope: item
- Reason: direct_download_ok
- Checked at: 2026-04-29T05:54:27.425Z
- Expires at: 2026-05-06T05:54:27.425Z
- Recommended action: Download for OpenClaw
## Links
- [Detail page](https://openagent3.xyz/skills/api-error-handling)
- [Send to Agent page](https://openagent3.xyz/skills/api-error-handling/agent)
- [JSON manifest](https://openagent3.xyz/skills/api-error-handling/agent.json)
- [Markdown brief](https://openagent3.xyz/skills/api-error-handling/agent.md)
- [Download page](https://openagent3.xyz/downloads/api-error-handling)