Command Palette

Search for a command to run...

UnylyUnyly
Back to skills

api-error-handling

FreeNo executable scriptsNot checked

Implement comprehensive API error handling with standardized error responses, logging, monitoring, and user-friendly messages. Use when building resilient…

diegosouzapwby diegosouzapw★ 68 GitHub stars

About this skill

API Error Handling

Overview

Build robust error handling systems with standardized error responses, detailed logging, error categorization, and user-friendly error messages.

When to Use

  • Handling API errors consistently
  • Debugging production issues
  • Implementing error recovery strategies
  • Monitoring error rates
  • Providing meaningful error messages to clients
  • Tracking error patterns

Instructions

1. Standardized Error Response Format

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Input validation failed",
    "statusCode": 422,
    "requestId": "req_abc123xyz789",
    "timestamp": "2025-01-15T10:30:00Z",
    "details": [
      {
        "field": "email",
        "message": "Invalid email format",
        "code": "INVALID_EMAIL"
      },
      {
        "field": "age",
        "message": "Must be at least 18",
        "code": "VALUE_OUT_OF_RANGE"
      }
    ],
    "path": "/api/users",
    "method": "POST",
    "traceId": "trace_001"
  }
}

2. Node.js Error Handling

const express = require('express');
const app = express();

// Error codes and mappings
const ERROR_CODES = {
  VALIDATION_ERROR: { status: 422, message: 'Validation failed' },
  NOT_FOUND: { status: 404, message: 'Resource not found' },
  UNAUTHORIZED: { status: 401, message: 'Authentication required' },
  FORBIDDEN: { status: 403, message: 'Access denied' },
  CONFLICT: { status: 409, message: 'Resource conflict' },
  RATE_LIMITED: { status: 429, message: 'Too many requests' },
  INTERNAL_ERROR: { status: 500, message: 'Internal server error' },
  SERVICE_UNAVAILABLE: { status: 503, message: 'Service unavailable' }
};

// Custom error class
class ApiError extends Error {
  constructor(code, message, statusCode = null, details = null) {
    super(message);
    this.code = code;
    this.statusCode = statusCode || ERROR_CODES[code]?.status || 500;
    this.details = details;
    this.timestamp = new Date().toISOString();
  }
}

// Global error handler middleware
app.use((err, req, res, next) => {
  const requestId = req.id || `req_${Date.now()}`;
  const traceId = req.traceId;

  // Log error
  logError(err, {
    requestId,
    traceId,
    method: req.method,
    path: req.path,
    query: req.query,
    userId: req.user?.id
  });

  // Handle different error types
  if (err instanceof ApiError) {
    return res.status(err.statusCode).json(formatErrorResponse(err, requestId, traceId));
  }

  if (err instanceof SyntaxError && 'body' in err) {
    const apiError = new ApiError('VALIDATION_ERROR', 'Invalid JSON', 400);
    return res.status(400).json(formatErrorResponse(apiError, requestId, traceId));
  }

  if (err.name === 'ValidationError') {
    const details = Object.keys(err.errors).map(field => ({
      field,
      message: err.errors[field].message,
      code: 'VALIDATION_FAILED'
    }));
    const apiError = new ApiError('VALIDATION_ERROR', 'Validation failed', 422, details);
    return res.status(422).json(formatErrorResponse(apiError, requestId, traceId));
  }

  if (err.name === 'CastError') {
    const apiError = new ApiError('NOT_FOUND', 'Invalid resource ID', 404);
    return res.status(404).json(formatErrorResponse(apiError, requestId, traceId));
  }

  // Unknown error
  const internalError = new ApiError('INTERNAL_ERROR', 'An unexpected error occurred', 500);
  res.status(500).json(formatErrorResponse(internalError, requestId, traceId));
});

// Error response formatter
function formatErrorResponse(error, requestId, traceId) {
  return {
    error: {
      code: error.code,
      message: error.message,
      statusCode: error.statusCode,
      requestId,
      timestamp: error.timestamp,
      ...(error.details && { details: error.details }),
      traceId
    }
  };
}

// Error logger
function logError(error, context) {
  const logData = {
    timestamp: new Date().toISOString(),
    errorCode: error.code,
    errorMessage: error.message,
    statusCode: error.statusCode,
    stack: error.stack,
    context
  };

  // Log to different levels based on severity
  if (error.statusCode >= 500) {
    console.error('[ERROR]', JSON.stringify(logData));
    // Send to error tracking service (Sentry, etc)
    trackError(logData);
  } else if (error.statusCode >= 400) {
    console.warn('[WARN]', JSON.stringify(logData));
  }
}

// Route with error handling
app.post('/api/users', async (req, res, next) => {
  try {
    const { email, firstName, lastName } = req.body;

    // Validation
    if (!email || !firstName || !lastName) {
      throw new ApiError(
        'VALIDATION_ERROR',
        'Missing required fields',
        422,
        [
          !email && { field: 'email', message: 'Email is required' },
          !firstName && { field: 'firstName', message: 'First name is required' },
          !lastName && { field: 'lastName', message: 'Last name is required' }
        ].filter(Boolean)
      );
    }

    // Check for conflicts
    const existing
Full SKILL.md on GitHub

Install api-error-handling in Claude Code & Claude Desktop

Sign up to install this skill

Create a free account to reveal the install command and save the skill to your library.

  • Reveal the one-line install command
  • Save skills to your synced library
  • Get notified when skills update
Sign up freeI already have an account

Allowed tools

Tools this skill is permitted to call.

No restriction — this skill can use any tool.

Bundled files

metadata.json

FAQ

What does the api-error-handling skill do?

Implement comprehensive API error handling with standardized error responses, logging, monitoring, and user-friendly messages. Use when building resilient APIs, debugging issues, or improving error reporting.

How do I install the api-error-handling skill?

Copy the skill folder into ~/.claude/skills (the Claude Code tab above does this in one command), or install it as a plugin.

Does the api-error-handling skill run scripts?

No, this skill is instructions only (SKILL.md) with no executable scripts.

Related skills

Compare api-error-handling with