Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
affaan-m avatar

Error Handling

  • 2.3k installs
  • 238k repo stars
  • Updated August 5, 2026
  • affaan-m/everything-claude-code

Patterns and implementations for consistent, robust error handling in TypeScript/JavaScript, Python, and Go production applications.

About

Comprehensive error handling guide for production applications spanning TypeScript, Python, and Go. Covers typed error hierarchies, Result patterns, API error handlers, React error boundaries, retry mechanisms with exponential backoff, and circuit breaker patterns. Emphasizes fail-fast principles, structured error types over strings, separation of user-facing and developer messages, and proper error propagation. Includes concrete implementations, checklists, and best practices for preventing silent failures, managing external dependencies reliably, and documenting error contracts in APIs.

  • Typed error hierarchies with code and status fields across three languages
  • Result pattern for expected failures without throwing exceptions
  • Exponential backoff retry logic with jitter and selective retry conditions
  • User-friendly error message mapping separate from internal details
  • React ErrorBoundary component for graceful frontend error handling

Error Handling by the numbers

  • 2,293 all-time installs (skills.sh)
  • +217 installs in the week ending Aug 5, 2026 (Skillselion tracking)
  • Ranked #235 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
  • Security screen: LOW risk (skills.sh audit)
  • Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/affaan-m/everything-claude-code --skill error-handling

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs2.3k
repo stars238k
Security audit3 / 3 scanners passed
Last updatedAugust 5, 2026
Repositoryaffaan-m/everything-claude-code

What it does

Design and implement robust error handling patterns across TypeScript, Python, and Go with typed errors, retry logic, and user-friendly messaging.

Who is it for?

Backend engineers building APIs, services with external dependencies, and full-stack applications requiring reliable error propagation and user-facing feedback.

Skip if: Frontend-only styling, static site generation, or applications without external dependencies or error recovery requirements.

When should I use this skill?

Designing new service error types, adding retry logic for unreliable dependencies, reviewing API error handling, implementing user-facing error messages, or debugging cascading failures.

What you get

Teams implement typed error hierarchies, fail-fast boundaries, selective retry logic, and clear separation between user and developer error context.

  • Typed error definitions
  • Retry and circuit-breaker implementations

By the numbers

  • Covers 3 languages: TypeScript, Python, and Go
  • Documents 5 core activation scenarios in the skill readme

Files

SKILL.mdMarkdownGitHub ↗

エラー処理パターン

本番アプリケーション向けの一貫した堅牢なエラー処理パターン。

アクティベートするタイミング

  • 新しいモジュールやサービスのエラー型や例外階層を設計する場合
  • 信頼性の低い外部依存関係に対してリトライロジックやサーキットブレーカーを追加する場合
  • APIエンドポイントでエラー処理の欠落をレビューする場合
  • ユーザー向けエラーメッセージとフィードバックを実装する場合
  • カスケード障害やサイレントなエラー飲み込みをデバッグする場合

コア原則

1. 早く大きく失敗する — エラーが発生した境界で表面化させる。埋め込まない 2. 文字列メッセージより型付きエラー — エラーは構造を持つファーストクラスの値 3. ユーザーメッセージ ≠ 開発者メッセージ — ユーザーには親しみやすいテキストを表示し、詳細なコンテキストはサーバー側でログに記録する 4. エラーをサイレントに飲み込まない — すべてのcatchブロックは処理、再スロー、またはログのいずれかを行う必要がある 5. エラーはAPIコントラクトの一部 — クライアントが受け取る可能性があるすべてのエラーコードをドキュメント化する

TypeScript / JavaScript

型付きエラークラス

// ドメインのエラー階層を定義する
export class AppError extends Error {
  constructor(
    message: string,
    public readonly code: string,
    public readonly statusCode: number = 500,
    public readonly details?: unknown,
  ) {
    super(message)
    this.name = this.constructor.name
    // トランスパイルされたES5 JavaScriptでプロトタイプチェーンを正しく維持する。
    // 組み込みのErrorクラスを拡張する際に`instanceof`チェック
    // (例: `error instanceof NotFoundError`)が正しく動作するために必要。
    Object.setPrototypeOf(this, new.target.prototype)
  }
}

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

export class ValidationError extends AppError {
  constructor(message: string, details: { field: string; message: string }[]) {
    super(message, 'VALIDATION_ERROR', 422, details)
  }
}

export class UnauthorizedError extends AppError {
  constructor(reason = 'Authentication required') {
    super(reason, 'UNAUTHORIZED', 401)
  }
}

export class RateLimitError extends AppError {
  constructor(public readonly retryAfterMs: number) {
    super('Rate limit exceeded', 'RATE_LIMITED', 429)
  }
}

Resultパターン(スロー不使用スタイル)

失敗が想定され一般的な操作(パース、外部呼び出し)向け:

type Result<T, E = AppError> =
  | { ok: true; value: T }
  | { ok: false; error: E }

function ok<T>(value: T): Result<T> {
  return { ok: true, value }
}

function err<E>(error: E): Result<never, E> {
  return { ok: false, error }
}

// 使用例
async function fetchUser(id: string): Promise<Result<User>> {
  try {
    const user = await db.users.findUnique({ where: { id } })
    if (!user) return err(new NotFoundError('User', id))
    return ok(user)
  } catch (e) {
    return err(new AppError('Database error', 'DB_ERROR'))
  }
}

const result = await fetchUser('abc-123')
if (!result.ok) {
  // TypeScriptはここでresult.errorを認識する
  logger.error('Failed to fetch user', { error: result.error })
  return
}
// TypeScriptはここでresult.valueを認識する
console.log(result.value.email)

APIエラーハンドラー(Next.js / Express)

import { NextRequest, NextResponse } from 'next/server'

function handleApiError(error: unknown): NextResponse {
  // 既知のアプリケーションエラー
  if (error instanceof AppError) {
    return NextResponse.json(
      {
        error: {
          code: error.code,
          message: error.message,
          ...(error.details ? { details: error.details } : {}),
        },
      },
      { status: error.statusCode },
    )
  }

  // Zodバリデーションエラー
  if (error instanceof z.ZodError) {
    return NextResponse.json(
      {
        error: {
          code: 'VALIDATION_ERROR',
          message: 'Request validation failed',
          details: error.issues.map(i => ({
            field: i.path.join('.'),
            message: i.message,
          })),
        },
      },
      { status: 422 },
    )
  }

  // 予期しないエラー — 詳細をログに記録し、汎用メッセージを返す
  console.error('Unexpected error:', error)
  return NextResponse.json(
    { error: { code: 'INTERNAL_ERROR', message: 'An unexpected error occurred' } },
    { status: 500 },
  )
}

export async function POST(req: NextRequest) {
  try {
    // ... ハンドラーロジック
  } catch (error) {
    return handleApiError(error)
  }
}

ReactエラーバウンダリーII

import { Component, ErrorInfo, ReactNode } from 'react'

interface Props {
  fallback: ReactNode
  onError?: (error: Error, info: ErrorInfo) => void
  children: ReactNode
}

interface State {
  hasError: boolean
  error: Error | null
}

export class ErrorBoundary extends Component<Props, State> {
  state: State = { hasError: false, error: null }

  static getDerivedStateFromError(error: Error): State {
    return { hasError: true, error }
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    this.props.onError?.(error, info)
    console.error('Unhandled React error:', error, info)
  }

  render() {
    if (this.state.hasError) return this.props.fallback
    return this.props.children
  }
}

// 使用例
<ErrorBoundary fallback={<p>Something went wrong. Please refresh.</p>}>
  <MyComponent />
</ErrorBoundary>

Python

カスタム例外階層

class AppError(Exception):
    """基底アプリケーションエラー。"""
    def __init__(self, message: str, code: str, status_code: int = 500):
        super().__init__(message)
        self.code = code
        self.status_code = status_code

class NotFoundError(AppError):
    def __init__(self, resource: str, id: str):
        super().__init__(f"{resource} not found: {id}", "NOT_FOUND", 404)

class ValidationError(AppError):
    def __init__(self, message: str, details: list[dict] | None = None):
        super().__init__(message, "VALIDATION_ERROR", 422)
        self.details = details or []

FastAPIグローバル例外ハンドラー

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

@app.exception_handler(AppError)
async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
    return JSONResponse(
        status_code=exc.status_code,
        content={"error": {"code": exc.code, "message": str(exc)}},
    )

@app.exception_handler(Exception)
async def generic_error_handler(request: Request, exc: Exception) -> JSONResponse:
    # 詳細をログに記録し、汎用メッセージを返す
    logger.exception("Unexpected error", exc_info=exc)
    return JSONResponse(
        status_code=500,
        content={"error": {"code": "INTERNAL_ERROR", "message": "An unexpected error occurred"}},
    )

Go

センチネルエラーとエラーラッピング

package domain

import "errors"

// 型チェック用センチネルエラー
var (
    ErrNotFound    = errors.New("not found")
    ErrUnauthorized = errors.New("unauthorized")
    ErrConflict     = errors.New("conflict")
)

// コンテキスト付きでエラーをラップする — 元のエラーを失わない
func (r *UserRepository) FindByID(ctx context.Context, id string) (*User, error) {
    user, err := r.db.QueryRow(ctx, "SELECT * FROM users WHERE id = $1", id)
    if errors.Is(err, sql.ErrNoRows) {
        return nil, fmt.Errorf("user %s: %w", id, ErrNotFound)
    }
    if err != nil {
        return nil, fmt.Errorf("querying user %s: %w", id, err)
    }
    return user, nil
}

// ハンドラーレベルでアンラップしてレスポンスを決定する
func (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {
    user, err := h.service.GetUser(r.Context(), chi.URLParam(r, "id"))
    if err != nil {
        switch {
        case errors.Is(err, domain.ErrNotFound):
            writeError(w, http.StatusNotFound, "not_found", err.Error())
        case errors.Is(err, domain.ErrUnauthorized):
            writeError(w, http.StatusForbidden, "forbidden", "Access denied")
        default:
            slog.Error("unexpected error", "err", err)
            writeError(w, http.StatusInternalServerError, "internal_error", "An unexpected error occurred")
        }
        return
    }
    writeJSON(w, http.StatusOK, user)
}

指数バックオフ付きリトライ

interface RetryOptions {
  maxAttempts?: number
  baseDelayMs?: number
  maxDelayMs?: number
  retryIf?: (error: unknown) => boolean
}

async function withRetry<T>(
  fn: () => Promise<T>,
  options: RetryOptions = {},
): Promise<T> {
  const {
    maxAttempts = 3,
    baseDelayMs = 500,
    maxDelayMs = 10_000,
    retryIf = () => true,
  } = options

  let lastError: unknown

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await fn()
    } catch (error) {
      lastError = error
      if (attempt === maxAttempts || !retryIf(error)) throw error

      const jitter = Math.random() * baseDelayMs
      const delay = Math.min(baseDelayMs * 2 ** (attempt - 1) + jitter, maxDelayMs)
      await new Promise(resolve => setTimeout(resolve, delay))
    }
  }

  throw lastError
}

// 使用例: 一時的なネットワークエラーはリトライ、4xxはリトライしない
const data = await withRetry(() => fetch('/api/data').then(r => r.json()), {
  maxAttempts: 3,
  retryIf: (error) => !(error instanceof AppError && error.statusCode < 500),
})

ユーザー向けエラーメッセージ

エラーコードを人間が読めるメッセージにマッピングする。技術的な詳細はユーザーに見えるテキストに含めない。

const USER_ERROR_MESSAGES: Record<string, string> = {
  NOT_FOUND: 'The requested item could not be found.',
  UNAUTHORIZED: 'Please sign in to continue.',
  FORBIDDEN: "You don't have permission to do that.",
  VALIDATION_ERROR: 'Please check your input and try again.',
  RATE_LIMITED: 'Too many requests. Please wait a moment and try again.',
  INTERNAL_ERROR: 'Something went wrong on our end. Please try again later.',
}

export function getUserMessage(code: string): string {
  return USER_ERROR_MESSAGES[code] ?? USER_ERROR_MESSAGES.INTERNAL_ERROR
}

エラー処理チェックリスト

エラー処理に触れるコードをマージする前に:

  • [ ] すべてのcatchブロックが処理、再スロー、またはログを行っている — サイレントな飲み込みなし
  • [ ] APIエラーが標準エンベロープ{ error: { code, message } }に従っている
  • [ ] ユーザー向けメッセージにスタックトレースや内部詳細が含まれていない
  • [ ] サーバー側で完全なエラーコンテキストがログに記録されている
  • [ ] カスタムエラークラスがcodeフィールドを持つ基底AppErrorを継承している
  • [ ] 非同期関数がエラーを呼び出し元に伝播している — フォールバックなしの fire-and-forget なし
  • [ ] リトライロジックがリトライ可能なエラーのみをリトライしている(4xxクライアントエラーはリトライしない)
  • [ ] ReactコンポーネントがレンダリングエラーのためにErrorBoundaryでラップされている

Related skills

Forks & variants (1)

Error Handling has 1 known copy in the catalog totaling 1.4k installs. They canonicalize to this original listing.

How it compares

Use error-handling for cross-language resilience patterns rather than framework-specific Semantic Kernel agent guidance.

FAQ

Which languages does error-handling cover?

The error-handling skill covers TypeScript, Python, and Go. It addresses typed errors, error boundaries, retries, circuit breakers, and user-facing messages for production applications.

When should error-handling be activated?

error-handling fits designing error types, adding retry or circuit breaker logic, reviewing API endpoints, implementing user-facing messages, or debugging cascading failures and silent error swallowing.

What patterns does error-handling emphasize?

error-handling emphasizes fail-fast behavior, explicit typed error hierarchies, circuit breakers for external dependencies, and clear user-facing messages. It originates from the Everything Claude Code collection.

Is Error Handling safe to install?

skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.

Backend & APIsbackendtesting

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.