Skip to main content
skill CX Codex

error-handling-standardizer — Claude Code skill: error handling

error-handling-standardizer is a skill that standardizes application errors across custom classes, HTTP responses, and structured logs for consistent API exception handling.

MIT 269 installs ★ 64 updated 2026-01-12

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add patricio0312rev/skills --skill error-handling-standardizer -a claude-code
Open on GitHub

What error-handling-standardizer does

The skill outlines an error hierarchy with AppError, ValidationError, NotFoundError, UnauthorizedError, and ForbiddenError, plus middleware for handling failures. Operational errors produce responses with their mapped status and code. Unknown errors return a generic 500 response with a request identifier; stack traces stay out of client responses.

The examples use TypeScript Express types and winston for logs containing error details and request context. An asyncHandler wrapper forwards rejected route promises to the middleware. Unknown failures become generic server errors, so check that this response fits your API’s error contract.

What it helps with

  • separate validation failures from programming errors
  • map error categories to HTTP status codes
  • keep internal error details out of client responses
  • add request context to error logs
  • forward async route failures to middleware

Example prompts for the agent

  • Standardize API errors with custom classes and matching HTTP status codes.
  • Add middleware that logs request context but returns safe messages to clients.
  • Review async routes and route their failures through a shared error handler.

How to install error-handling-standardizer

1Skills CLI (Vercel)

npx skills add patricio0312rev/skills --skill error-handling-standardizer -a claude-code

2Manually: put the files in place

~/.claude/skills/error-handling-standardizer/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/error-handling-standardizer/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about error-handling-standardizer

How do I install error-handling-standardizer in Claude Code?

Run npx skills add patricio0312rev/skills --skill error-handling-standardizer -a claude-code. The skill file is at ~/.claude/skills/error-handling-standardizer/SKILL.md.

What does error-handling-standardizer do?

It provides patterns for consistent error classes, HTTP responses, and structured logs. It also covers middleware and wrapping asynchronous route handlers.

What happens to unknown errors?

The middleware returns a generic HTTP 500 response with a request identifier. It keeps the stack trace in the log rather than exposing it to the client.

Source text

SKILL.md · MIT
---
name: error-handling-standardizer
description: Creates consistent error handling with custom error classes, HTTP status mapping, structured logging, safe client messages, and error taxonomy. Use when standardizing "error handling", "logging", "error responses", or "exception management".
---

# Error Handling Standardizer

Build consistent, debuggable error handling across the application.

## Error Taxonomy

```typescript
export class AppError extends Error {
  constructor(
    public code: string,
    public message: string,
    public statusCode: number = 500,
    public isOperational: boolean = true,
    public details?: any
  ) {
    super(message);
    Error.captureStackTrace(this, this.constructor);
  }
}

export class ValidationError extends AppError {
  constructor(details: Record<string, string[]>) {
    super("VALIDATION_ERROR", "Validation failed", 400, true, details);
  }
}

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

export class UnauthorizedError extends AppError {
  constructor(message = "Unauthorized") {
    super("UNAUTHORIZED", message, 401);
  }
}

export class ForbiddenError extends AppError {
  constructor(message = "Forbidden") {
    super("FORBIDDEN", message, 403);
  }
}
```

## Error Handler Middleware

```typescript
export const errorHandler = (
  err: Error,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  // Log error
  logger.error("Request error", {
    error: err.message,
    stack: err.stack,
    path: req.path,
    method: req.method,
    requestId: req.id,
  });

  // Operational errors (known)
  if (err instanceof AppError && err.isOperational) {
    return res.status(err.statusCode).json({
      success: false,
      error: {
        code: err.code,
        message: err.message,
        details: err.details,
        trace_id: req.id,
      },
    });
  }

  // Programming errors (unknown)
  return res.status(500).json({
    success: false,
    error: {
      code: "INTERNAL_ERROR",
      message: "An unexpected error occurred",
      trace_id: req.id,
    },
  });
};
```

## Structured Logging

```typescript
import winston from "winston";

export const logger = winston.createLogger({
  level: "info",
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.errors({ stack: true }),
    winston.format.json()
  ),
  transports: [
    new winston.transports.File({ filename: "error.log", level: "error" }),
    new winston.transports.File({ filename: "combined.log" }),
  ],
});

// Log with context
logger.error("Payment processing failed", {
  userId: user.id,
  amount: payment.amount,
  error: err.message,
  trace_id: req.id,
});
```

## Safe Client Messages

```typescript
// Never expose internal errors to clients
const getSafeErrorMessage = (err: Error): string => {
  if (err instanceof AppError && err.isOperational) {
    return err.message; // Safe, user-facing message
  }

  // Generic message for unexpected errors
  return "An unexpected error occurred";
};
```

## Async Error Handling

```typescript
// Wrap async routes
export const asyncHandler = (fn: RequestHandler) => {
  return (req: Request, res: Response, next: NextFunction) => {
    Promise.resolve(fn(req, res, next)).catch(next);
  };
};

// Usage
router.get(
  "/users",
  asyncHandler(async (req, res) => {
    const users = await userService.findAll();
    res.json(users);
  })
);
```

## Best Practices

- Use custom error classes
- Distinguish operational vs programming errors
- Log all errors with context
- Never expose stack traces to clients
- Include trace IDs for debugging
- Monitor error rates by type
- Set up alerting for critical errors

## Output Checklist

- [ ] Custom error classes defined
- [ ] Error handler middleware
- [ ] HTTP status code mapping
- [ ] Structured logging setup
- [ ] Safe client error messages
- [ ] Async error wrapper
- [ ] Error monitoring/alerts
- [ ] Documentation of error codes

© patricio0312rev · MIT · patricio0312rev/skills

Similar skills

All skills for Backend and APIs →

From the same set148

The whole set →
threat-model-generator threat-model-generator builds a STRIDE threat model: lists assets, enumerates threats with risk scores, picks mitigations and works out what risk is left. CX Codex +1 270installs domain-model-boundaries-mapper domain-model-boundaries-mapper maps domain areas, module ownership, dependencies, and interfaces in a codebase. Useful when untangling a monolith or planning a domain-driven redesign. CX Codex +1 270installs react-hook-builder react-hook-builder generates production-grade custom React hooks in TypeScript for data fetching, forms, and local storage. CX Codex +1 269installs mcp-server-builder mcp-server-builder is a Claude Code skill for building MCP servers with tools, resources, and prompts. It activates on requests for an MCP integration or custom Claude tools. CX Codex +1 269installs tech-debt-prioritizer The tech-debt-prioritizer skill scores technical debt by impact, risk, and effort, then ranks the work. Use it to decide which codebase issues to tackle first. CX Codex +1 268installs integration-test-builder integration-test-builder — a skill for building integration tests for APIs and database flows. Generates test harness, fixtures, setup/teardown, database seeding, and CI-ready strategies. CX Codex +1 267installs tanstack-query-setup tanstack-query-setup sets up TanStack Query in a React app: a QueryClient provider, fetch hooks, mutations and cache rules. The agent gets templates it can fill with your code. CX Codex +1 267installs hot-reload-optimizer The hot-reload-optimizer skill for Claude Code fine-tunes hot module replacement and fast refresh in Vite, Next.js, and webpack projects when local rebuilds lag. CX Codex +1 267installs

Project sponsors

Companies that keep this analytics open