api-error-handling

Apply when designing error responses, implementing error handlers, and ensuring consistent error format across APIs.

16 stars

Best use case

api-error-handling is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Apply when designing error responses, implementing error handlers, and ensuring consistent error format across APIs.

Teams using api-error-handling should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/api-error-handling/SKILL.md --create-dirs "https://raw.githubusercontent.com/diegosouzapw/awesome-omni-skill/main/skills/backend/api-error-handling/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/api-error-handling/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How api-error-handling Compares

Feature / Agentapi-error-handlingStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Apply when designing error responses, implementing error handlers, and ensuring consistent error format across APIs.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

## When to Use

Apply when designing error responses, implementing error handlers, and ensuring consistent error format across APIs.

## Patterns

### Pattern 1: Standard Error Response Format
```typescript
// Source: https://www.rfc-editor.org/rfc/rfc9457 (Problem Details)
interface ApiError {
  error: {
    code: string;           // Machine-readable code
    message: string;        // Human-readable message
    details?: ErrorDetail[];// Field-level errors
    requestId?: string;     // For debugging
  };
}

interface ErrorDetail {
  field: string;
  message: string;
  code?: string;
}

// Example response
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request validation failed",
    "details": [
      { "field": "email", "message": "Invalid email format", "code": "INVALID_FORMAT" },
      { "field": "age", "message": "Must be positive", "code": "INVALID_RANGE" }
    ],
    "requestId": "req_abc123"
  }
}
```

### Pattern 2: Error Class Hierarchy
```typescript
// Source: Best practice pattern
class AppError extends Error {
  constructor(
    public code: string,
    message: string,
    public statusCode: number,
    public details?: ErrorDetail[]
  ) {
    super(message);
    this.name = 'AppError';
  }
}

class ValidationError extends AppError {
  constructor(details: ErrorDetail[]) {
    super('VALIDATION_ERROR', 'Validation failed', 400, details);
  }
}

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

class UnauthorizedError extends AppError {
  constructor() {
    super('UNAUTHORIZED', 'Authentication required', 401);
  }
}
```

### Pattern 3: Global Error Handler (Express/Next.js)
```typescript
// Source: Best practice pattern
function errorHandler(
  err: Error,
  req: Request,
  res: Response,
  next: NextFunction
) {
  // Log for debugging
  console.error('Error:', {
    message: err.message,
    stack: err.stack,
    requestId: req.headers['x-request-id'],
  });

  if (err instanceof AppError) {
    return res.status(err.statusCode).json({
      error: {
        code: err.code,
        message: err.message,
        details: err.details,
        requestId: req.headers['x-request-id'],
      },
    });
  }

  // Unknown error - don't leak details
  return res.status(500).json({
    error: {
      code: 'INTERNAL_ERROR',
      message: 'An unexpected error occurred',
      requestId: req.headers['x-request-id'],
    },
  });
}
```

### Pattern 4: Frontend Error Handling
```typescript
// Source: Best practice pattern
async function apiCall<T>(url: string, options?: RequestInit): Promise<T> {
  const response = await fetch(url, options);

  if (!response.ok) {
    const error = await response.json();
    throw new ApiError(error.error.code, error.error.message, error.error.details);
  }

  return response.json();
}

// Usage with error handling
try {
  const user = await apiCall<User>('/api/users/123');
} catch (error) {
  if (error instanceof ApiError) {
    if (error.code === 'NOT_FOUND') {
      showNotification('User not found');
    } else if (error.code === 'VALIDATION_ERROR') {
      setFormErrors(error.details);
    }
  }
}
```

### Pattern 5: Error Code Constants
```typescript
// Source: Best practice pattern
export const ErrorCodes = {
  VALIDATION_ERROR: 'VALIDATION_ERROR',
  NOT_FOUND: 'NOT_FOUND',
  UNAUTHORIZED: 'UNAUTHORIZED',
  FORBIDDEN: 'FORBIDDEN',
  CONFLICT: 'CONFLICT',
  RATE_LIMITED: 'RATE_LIMITED',
  INTERNAL_ERROR: 'INTERNAL_ERROR',
} as const;

type ErrorCode = typeof ErrorCodes[keyof typeof ErrorCodes];
```

## Anti-Patterns

- **Exposing stack traces** - Never in production
- **Generic "Error occurred"** - Provide actionable messages
- **200 for errors** - Use appropriate HTTP status codes
- **Inconsistent format** - Same structure for all errors

## Verification Checklist

- [ ] All errors have code + message
- [ ] Status codes match error type
- [ ] Validation errors include field details
- [ ] Stack traces hidden in production
- [ ] Request ID for debugging correlation

Related Skills

gdpr-data-handling

16
from diegosouzapw/awesome-omni-skill

Implement GDPR-compliant data handling with consent management, data subject rights, and privacy by design. Use when building systems that process EU personal data, implementing privacy controls, o...

error-diagnostics-smart-debug

16
from diegosouzapw/awesome-omni-skill

Use when working with error diagnostics smart debug

error-detective

16
from diegosouzapw/awesome-omni-skill

Search logs and codebases for error patterns, stack traces, and anomalies. Correlates errors across systems and identifies root causes. Use PROACTIVELY when debugging issues, analyzing logs, or investigating production errors.

error-debugging-multi-agent-review

16
from diegosouzapw/awesome-omni-skill

Use when working with error debugging multi agent review

agent-error-detective

16
from diegosouzapw/awesome-omni-skill

Expert error detective specializing in complex error pattern analysis, correlation, and root cause discovery. Masters distributed system debugging, error tracking, and anomaly detection with focus on finding hidden connections and preventing error cascades.

Qiskit Cirq Quantum Error

16
from diegosouzapw/awesome-omni-skill

This skill covers the development of software for quantum computers, focusing on quantum algorithms, quantum error correction, and hybrid quantum-classical applications. It includes using quantum SDKs

Error Shape Taxonomy

16
from diegosouzapw/awesome-omni-skill

Organization-wide standard error response format covering error codes, categories, and structure that enables clients and monitoring tools to understand errors immediately.

Error Boundaries React

16
from diegosouzapw/awesome-omni-skill

Error boundaries are React components that catch JavaScript errors anywhere in their component tree, log those errors, and display a fallback UI instead of a component tree that crashed. Introduced in

api-error-taxonomy

16
from diegosouzapw/awesome-omni-skill

Define consistent API error codes and responses. Use when a mid-level developer needs error standardization.

aiwf:error-tracking

16
from diegosouzapw/awesome-omni-skill

Add Sentry v8 error tracking and performance monitoring to your project services. Use this skill when adding error handling, creating new controllers, instrumenting cron jobs, or tracking database performance. ALL ERRORS MUST BE CAPTURED TO SENTRY - no exceptions.

cfn-error-management

16
from diegosouzapw/awesome-omni-skill

Unified error handling, batching, and logging for CFN Loop. Use when you need to capture agent errors, batch multiple errors for processing, log structured error data, or categorize and recover from agent failures.

agent-error-coordinator

16
from diegosouzapw/awesome-omni-skill

Expert error coordinator specializing in distributed error handling, failure recovery, and system resilience. Masters error correlation, cascade prevention, and automated recovery strategies across multi-agent systems with focus on minimizing impact and learning from failures.