Agent skill

Error Handling

by MadAppGang in MadAppGang/claude-code

A skill your agent uses when implementing custom error classes, error middleware, structured logging, retry logic, or graceful shutdown patterns in backend applications.

MITAuto-check passedDevelopment

Install Error Handling

skills CLI
$ npx skills add MadAppGang/claude-code --skill error-handling -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install MadAppGang/claude-code error-handling --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/MadAppGang/claude-code.git skills-src && mkdir -p .claude/skills && cp -r skills-src/plugins/dev/skills/backend/error-handling .claude/skills/error-handling && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
error-handling
GitHub stars
285
Token cost
~2.6k tokens
SKILL.md length
55 words
Files
1
Skills in repo
69
Repo updated
First seen
Licence
MIT

At a glance

A skill your agent uses when implementing custom error classes, error middleware, structured logging, retry logic, or graceful shutdown patterns in backend applications.

  • Implementing custom error classes
  • SKILL.md covers Overview, Error Types, Error Response Format and Error Handling Middleware, plus 6 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md
  • Error middleware

What it does

Error Handling is an agent skill from MadAppGang/claude-code. Use when implementing custom error classes, error middleware, structured logging, retry logic, or graceful shutdown patterns in backend applications.

Its SKILL.md is about 2.6k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Development, covering Error handling and Observability. The repository describes itself as: claude code plugins marketplace. The licence is MIT.

When your agent uses it

  • Implementing custom error classes
  • Error middleware
  • Structured logging
  • Graceful shutdown patterns in backend applications

Example prompts

  • “/error-handling”

What it can do on your machine

Read from SKILL.md and the folder at commit 6097ad4. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript and json).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Error Handling loads about 2.6k tokens when it runs. Until then it costs about 41 tokens; SKILL.md has 55 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~41
When it runs · the whole SKILL.md, loaded when a task matches
~2.6k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from MadAppGang/claude-code at commit 6097ad4, republished under its MIT licence (© MadAppGang). 55 words, ~2,559 tokens.

Download SKILL.mdSave it as .claude/skills/error-handling/SKILL.md (or your agent's skills folder).
name
error-handling
description
Use when implementing custom error classes, error middleware, structured logging, retry logic, or graceful shutdown patterns in backend applications.
version
1.0.0
keywords
error handling, custom errors, error middleware, logging, retry logic, graceful shutdown, error responses, debugging
plugin
dev
updated
2026-01-20

Error Handling Patterns

Overview

Backend error handling patterns for building robust and debuggable services.

Error Types

Custom Error Classes
typescript
// Base application error
class AppError extends Error {
  constructor(
    message: string,
    public code: string,
    public statusCode: number = 500,
    public isOperational: boolean = true
  ) {
    super(message);
    this.name = this.constructor.name;
    Error.captureStackTrace(this, this.constructor);
  }
}

// Specific error types
class ValidationError extends AppError {
  constructor(message: string, public fields?: Record<string, string>) {
    super(message, 'VALIDATION_ERROR', 400);
  }
}

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

class UnauthorizedError extends AppError {
  constructor(message: string = 'Unauthorized') {
    super(message, 'UNAUTHORIZED', 401);
  }
}

class ForbiddenError extends AppError {
  constructor(message: string = 'Forbidden') {
    super(message, 'FORBIDDEN', 403);
  }
}

class ConflictError extends AppError {
  constructor(message: string) {
    super(message, 'CONFLICT', 409);
  }
}

class RateLimitError extends AppError {
  constructor(public retryAfter: number) {
    super('Too many requests', 'RATE_LIMIT', 429);
  }
}

Error Response Format

Standard Format
typescript
interface ErrorResponse {
  error: {
    code: string;
    message: string;
    details?: unknown;
    stack?: string;  // Only in development
  };
  meta: {
    requestId: string;
    timestamp: string;
  };
}

function formatError(error: AppError, requestId: string): ErrorResponse {
  const response: ErrorResponse = {
    error: {
      code: error.code,
      message: error.message,
    },
    meta: {
      requestId,
      timestamp: new Date().toISOString(),
    },
  };

  if (error instanceof ValidationError && error.fields) {
    response.error.details = error.fields;
  }

  if (process.env.NODE_ENV === 'development') {
    response.error.stack = error.stack;
  }

  return response;
}
Example Responses
json
// Validation error
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input data",
    "details": {
      "email": "Invalid email format",
      "password": "Must be at least 8 characters"
    }
  },
  "meta": {
    "requestId": "req_abc123",
    "timestamp": "2024-01-15T10:30:00Z"
  }
}

// Not found error
{
  "error": {
    "code": "NOT_FOUND",
    "message": "User with id 123 not found"
  },
  "meta": {
    "requestId": "req_def456",
    "timestamp": "2024-01-15T10:30:00Z"
  }
}

// Server error (production)
{
  "error": {
    "code": "INTERNAL_ERROR",
    "message": "An unexpected error occurred"
  },
  "meta": {
    "requestId": "req_ghi789",
    "timestamp": "2024-01-15T10:30:00Z"
  }
}

Error Handling Middleware

Express Middleware
typescript
import { Request, Response, NextFunction } from 'express';

// Async handler wrapper
function asyncHandler(fn: Function) {
  return (req: Request, res: Response, next: NextFunction) => {
    Promise.resolve(fn(req, res, next)).catch(next);
  };
}

// Error handler middleware
function errorHandler(
  error: Error,
  req: Request,
  res: Response,
  next: NextFunction
) {
  const requestId = req.headers['x-request-id'] as string || generateId();

  // Log error
  logger.error('Request failed', {
    requestId,
    error: error.message,
    stack: error.stack,
    path: req.path,
    method: req.method,
  });

  // Handle known errors
  if (error instanceof AppError) {
    return res.status(error.statusCode).json(
      formatError(error, requestId)
    );
  }

  // Handle unknown errors
  const internalError = new AppError(
    process.env.NODE_ENV === 'production'
      ? 'An unexpected error occurred'
      : error.message,
    'INTERNAL_ERROR',
    500,
    false  // Not operational
  );

  res.status(500).json(formatError(internalError, requestId));
}

// Usage
app.get('/users/:id', asyncHandler(async (req, res) => {
  const user = await userService.findById(req.params.id);
  if (!user) throw new NotFoundError('User', req.params.id);
  res.json({ data: user });
}));

app.use(errorHandler);

Validation Errors

Zod Validation
typescript
import { z, ZodError } from 'zod';

const createUserSchema = z.object({
  email: z.string().email('Invalid email format'),
  password: z.string().min(8, 'Password must be at least 8 characters'),
  name: z.string().min(2, 'Name must be at least 2 characters'),
});

function validateBody<T>(schema: z.Schema<T>) {
  return (req: Request, res: Response, next: NextFunction) => {
    try {
      req.body = schema.parse(req.body);
      next();
    } catch (error) {
      if (error instanceof ZodError) {
        const fields = error.errors.reduce((acc, err) => {
          acc[err.path.join('.')] = err.message;
          return acc;
        }, {} as Record<string, string>);
        throw new ValidationError('Invalid input data', fields);
      }
      throw error;
    }
  };
}

// Usage
app.post('/users', validateBody(createUserSchema), createUser);

Database Error Handling

typescript
import { DatabaseError, UniqueConstraintError } from 'pg';

function handleDatabaseError(error: Error): AppError {
  if (error instanceof UniqueConstraintError) {
    return new ConflictError('Resource already exists');
  }

  if (error.message.includes('foreign key')) {
    return new ValidationError('Referenced resource does not exist');
  }

  // Log unexpected database errors
  logger.error('Database error', { error: error.message });
  return new AppError('Database operation failed', 'DATABASE_ERROR', 500);
}

// Repository example
async function createUser(data: CreateUserInput): Promise<User> {
  try {
    return await db.users.create(data);
  } catch (error) {
    throw handleDatabaseError(error);
  }
}

External Service Errors

typescript
class ExternalServiceError extends AppError {
  constructor(
    service: string,
    public originalError?: Error
  ) {
    super(
      `External service ${service} failed`,
      'EXTERNAL_SERVICE_ERROR',
      503
    );
  }
}

async function callExternalAPI(url: string) {
  try {
    const response = await fetch(url, {
      signal: AbortSignal.timeout(5000), // 5 second timeout
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    if (error.name === 'AbortError') {
      throw new ExternalServiceError('API', new Error('Timeout'));
    }
    throw new ExternalServiceError('API', error);
  }
}

Retry Logic

typescript
interface RetryOptions {
  maxAttempts: number;
  baseDelay: number;
  maxDelay: number;
  shouldRetry?: (error: Error) => boolean;
}

async function withRetry<T>(
  fn: () => Promise<T>,
  options: RetryOptions
): Promise<T> {
  const { maxAttempts, baseDelay, maxDelay, shouldRetry } = options;

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await fn();
    } catch (error) {
      const canRetry = shouldRetry?.(error) ?? true;

      if (!canRetry || attempt === maxAttempts) {
        throw error;
      }

      const delay = Math.min(
        baseDelay * Math.pow(2, attempt - 1),
        maxDelay
      );

      logger.warn('Retrying operation', {
        attempt,
        maxAttempts,
        delay,
        error: error.message,
      });

      await sleep(delay);
    }
  }

  throw new Error('Unreachable');
}

// Usage
const result = await withRetry(
  () => externalAPI.call(),
  {
    maxAttempts: 3,
    baseDelay: 1000,
    maxDelay: 10000,
    shouldRetry: (error) => error instanceof ExternalServiceError,
  }
);

Logging Best Practices

typescript
// Structured logging
interface LogContext {
  requestId?: string;
  userId?: string;
  [key: string]: unknown;
}

const logger = {
  info: (message: string, context?: LogContext) => {
    console.log(JSON.stringify({ level: 'info', message, ...context }));
  },

  warn: (message: string, context?: LogContext) => {
    console.log(JSON.stringify({ level: 'warn', message, ...context }));
  },

  error: (message: string, context?: LogContext & { error?: string; stack?: string }) => {
    console.error(JSON.stringify({ level: 'error', message, ...context }));
  },
};

// Error logging middleware
function logErrors(error: Error, req: Request, res: Response, next: NextFunction) {
  logger.error('Request error', {
    requestId: req.headers['x-request-id'] as string,
    userId: req.user?.id,
    path: req.path,
    method: req.method,
    error: error.message,
    stack: error.stack,
  });
  next(error);
}

Graceful Shutdown

typescript
async function gracefulShutdown(signal: string) {
  logger.info('Shutdown signal received', { signal });

  // Stop accepting new requests
  server.close(() => {
    logger.info('HTTP server closed');
  });

  // Close database connections
  await db.close();
  logger.info('Database connections closed');

  // Close other resources
  await redis.quit();
  logger.info('Redis connection closed');

  process.exit(0);
}

process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));

// Handle uncaught errors
process.on('uncaughtException', (error) => {
  logger.error('Uncaught exception', { error: error.message, stack: error.stack });
  gracefulShutdown('uncaughtException');
});

process.on('unhandledRejection', (reason) => {
  logger.error('Unhandled rejection', { reason: String(reason) });
  gracefulShutdown('unhandledRejection');
});

Error handling patterns for robust backend services

© MadAppGang, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in plugins/dev/skills/backend/error-handling of MadAppGang/claude-code.

Open the folder on GitHubat commit 6097ad4

Compare with similar skills

Error Handling next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Error Handling compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Error Handling this skillMadAppGang/claude-code285—~2.6kAutomated safety check: PassMIT
evlog Map Rule Creatorevloghq/evlog1.9k—~2.9kAutomated safety check: PassMIT
fp-go Logging PatternsIBM/fp-go2k—~3.7kAutomated safety check: PassApache-2.0
Rust SkillsJMBeresford/retrom2.1k1 repos~9.5kAutomated safety check: PassMIT
Logging and Error Reporting for Warpwarpdotdev/warp65k1 repos~5.6kAutomated safety check: PassAGPL-3.0
Error HandlingCloudAI-X/claude-workflow-v21.4k—~3.4kAutomated safety check: PassMIT

Similar skills

  • Walks through adding a new rule or framework adapter to `evlog map` in @evlog/cli, from the rule source and registry to types, tests, docs and the published skill.

    1.9k GitHub stars~2.9k tokensUpdated today
    DevelopmentAuto-check passed
  • Official

    Adds logging to fp-go functional pipelines with Tap operators, entry and exit logs and error context, so that logging never changes the value or error flowing through.

    2k GitHub stars~3.7k tokensUpdated yesterday
    DevelopmentAuto-check passed
  • Rust Skills

    JMBeresford/retrom

    Comprehensive Rust coding guidelines with 265 rules across 26 categories.

    2.1k GitHub starsUsed in 1 repo~9.5k tokens
    DevelopmentAuto-check passed
  • Guides log level choices and when to raise a structured Sentry event instead of a plain log line in the Warp Rust codebase, keeping secrets out of logs.

    65k GitHub starsUsed in 1 repo~5.6k tokens
    DevelopmentAuto-check passed
  • Error Handling

    CloudAI-X/claude-workflow-v2

    Implements error handling patterns, structured logging, retry strategies, circuit breakers, and graceful degradation.

    1.4k GitHub stars~3.4k tokensUpdated 3 days ago
    DevelopmentAuto-check passed
  • Logging Observability

    getsentry/toolkit

    Official

    Review code for correct logging and error handling patterns.

    918 GitHub stars~2.6k tokensUpdated today
    DevOps & CloudAuto-check passed

More from MadAppGang/claude-code

All 69 skills in this repo
  • Content Brief

    MadAppGang/claude-code

    Content brief template and creation methodology for SEO-optimized content.

    285 GitHub starsUsed in 1 repo~959 tokens
    Auto-check passed
  • Context Detection

    MadAppGang/claude-code

    A skill your agent uses when detecting project technology stack from files/configs/directory structure, auto-loading framework-specific skills, or analyzing multi-stack fullstack projects (e.g…

    285 GitHub stars~5.4k tokensUpdated 6 mo ago
    Auto-check passed
  • Content Optimizer

    MadAppGang/claude-code

    On-page SEO optimization techniques including keyword density, meta tags, heading structure, and readability.

    285 GitHub starsUsed in 1 repo~694 tokens
    Auto-check passed
  • Keyword Cluster Builder

    MadAppGang/claude-code

    Techniques for expanding seed keywords and clustering by topic and intent.

    285 GitHub starsUsed in 1 repo~674 tokens
    Auto-check passed
  • Serp Analysis

    MadAppGang/claude-code

    SERP analysis techniques for intent classification, feature identification, and competitive intelligence.

    285 GitHub starsUsed in 1 repo~1k tokens
    Auto-check passed
  • Agent Coordination Discipline

    MadAppGang/claude-code

    A skill your agent uses when deciding whether to launch an agent, selecting which agent to use, or coordinating multiple agents.

    285 GitHub stars~3.8k tokensUpdated 6 mo ago
    Auto-check passed

Categories

Questions about Error Handling

What does Error Handling do?

A skill your agent uses when implementing custom error classes, error middleware, structured logging, retry logic, or graceful shutdown patterns in backend applications. Error Handling is an agent skill from MadAppGang/claude-code. Use when implementing custom error classes, error middleware, structured logging, retry logic, or graceful shutdown patterns in backend applications.

When should I use Error Handling?

Error Handling fits situations like: implementing custom error classes; error middleware; structured logging; graceful shutdown patterns in backend applications.

How do I install Error Handling in Claude Code?

Run `npx skills add MadAppGang/claude-code --skill error-handling -a claude-code`. Or copy the skill folder (plugins/dev/skills/backend/error-handling in MadAppGang/claude-code) into .claude/skills/error-handling in your project. Claude Code loads it when a task matches its description.

How do I install Error Handling in Codex?

Run `npx skills add MadAppGang/claude-code --skill error-handling -a codex`. Or copy the skill folder (plugins/dev/skills/backend/error-handling in MadAppGang/claude-code) into .agents/skills/error-handling in your project. Codex loads it when a task matches its description.

Can I use Error Handling in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add MadAppGang/claude-code --skill error-handling -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/error-handling, .gemini/skills/error-handling, .github/skills/error-handling and .opencode/skills/error-handling in your project.

What does Error Handling need to run?

SKILL.md names no scripts, command-line tools or credentials: Error Handling is instructions for the agent only.

Does Error Handling access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Error Handling safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Error Handling use?

Error Handling is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Error Handling use?

About 2.6k tokens (SKILL.md is roughly 10k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Error Handling?

Skills that share tags, products or a category with Error Handling: evlog Map Rule Creator (evloghq/evlog, 1.9k stars), fp-go Logging Patterns (IBM/fp-go, 2k stars), Rust Skills (JMBeresford/retrom, 2.1k stars) and Logging and Error Reporting for Warp (warpdotdev/warp, 65k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Error Handling?

MadAppGang (a GitHub organization) maintains it in MadAppGang/claude-code, which has 285 GitHub stars. The repository holds 69 skills in this directory. The repository was last updated on March 15, 2026.

Source: MadAppGang/claude-code on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.