CLSkills
API Developmentbeginner

API Error Handler

Share

Create standardized API error handling

API Error Handler

Create standardized API error handling

Create standardized API error handling.

Instructions

  1. Define error classes:
class AppError extends Error {
  constructor(
    public statusCode: number,
    public code: string,
    message: string,
    public details?: unknown
  ) {
    super(message);
  }
}

class ValidationError extends AppError {
  constructor(details: unknown) {
    super(400, 'VALIDATION_ERROR', 'Invalid request data', details);
  }
}
class NotFoundError extends AppError {
  constructor(resource: string) {
    super(404, 'NOT_FOUND', `${resource} not found`);
  }
}
class UnauthorizedError extends AppError {
  constructor() { super(401, 'UNAUTHORIZED', 'Authentication required'); }
}
class ForbiddenError extends AppError {
  constructor() { super(403, 'FORBIDDEN', 'Insufficient permissions'); }
}
class ConflictError extends AppError {
  constructor(message: string) { super(409, 'CONFLICT', message); }
}
  1. Error handler middleware:
function handleError(err: unknown): Response {
  if (err instanceof AppError) {
    return Response.json({
      error: { code: err.code, message: err.message, details: err.details }
    }, { status: err.statusCode });
  }
  // Unknown error — log full details, return generic message
  console.error('Unhandled error:', err);
  return Response.json({
    error: { code: 'INTERNAL_ERROR', message: 'Something went wrong' }
  }, { status: 500 });
}

Rules

  • Never expose stack traces to clients
  • Log full error details server-side
  • Use consistent error shape: { error: { code, message, details? } }

Quick Info

Difficultybeginner
Version1.0.0
AuthorClaude Skills Hub
apierrorshandling

Install command:

curl -o ~/.claude/skills/api-error-handler.md https://claude-skills-hub.vercel.app/skills/api/api-error-handler.md