Index of every page on this site: llms.txt
All skills
jeremylongshore avatar

/handling-api-errors

@820dfc8
Run it yourself

Implement standardized error handling with proper HTTP status codes and error responses. Use when implementing standardized error handling. Trigger with phrases like "add error handling", "standardize errors", or "implement error responses".

Use this Skill: https://skilld.dev/gh/jeremylongshore/tons-of-skills-marketplace/handling-api-errors

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesexamples.md

≈1.5k tokens on demand. Your agent reads this file only when SKILL.md points to it.

API Error Handling Examples

RFC 7807 Problem Details Response

{
  "type": "https://api.example.com/errors/validation",
  "title": "Validation Error",
  "status": 400,
  "detail": "Request body contains 2 validation errors",
  "instance": "/users",
  "errors": [
    { "field": "email", "message": "Invalid email format", "code": "INVALID_FORMAT" },
    { "field": "name", "message": "Must be at least 1 character", "code": "TOO_SHORT" }
  ]
}

Typed Error Classes

// errors/http-errors.js
class AppError extends Error {
  constructor(message, status, type, details = {}) {
    super(message);
    this.status = status;
    this.type = type;
    this.details = details;
  }
  toRFC7807(path) {
    return {
      type: `https://api.example.com/errors/${this.type}`,
      title: this.message, status: this.status,
      detail: this.details.detail || this.message,
      instance: path, ...this.details,
    };
  }
}

class ValidationError extends AppError {
  constructor(errors) { super('Validation Error', 400, 'validation', { errors }); }
}
class NotFoundError extends AppError {
  constructor(resource, id) {
    super('Not Found', 404, 'not-found', { detail: `${resource} '${id}' not found` });
  }
}
class ConflictError extends AppError {
  constructor(field, value) {
    super('Conflict', 409, 'conflict', { detail: `${field} '${value}' already exists` });
  }
}
class AuthenticationError extends AppError {
  constructor(detail = 'Invalid or missing authentication') {
    super('Authentication Required', 401, 'authentication', { detail });
  }
}
class RateLimitError extends AppError {
  constructor(retryAfter) {
    super('Too Many Requests', 429, 'rate-limit', { detail: 'Rate limit exceeded', retryAfter });
  }
}

Centralized Error Handler Middleware

// middleware/error-handler.js
function errorHandler(err, req, res, next) {
  const correlationId = req.headers['x-request-id'] || crypto.randomUUID();

  if (err instanceof AppError) {
    const body = err.toRFC7807(req.originalUrl);
    body.correlationId = correlationId;
    logger.warn({ err, correlationId, path: req.originalUrl });
    return res.status(err.status).json(body);
  }

  if (err.name === 'ZodError') {
    const errors = err.issues.map(i => ({
      field: i.path.join('.'), message: i.message, code: i.code,
    }));
    return res.status(400).json({
      type: 'https://api.example.com/errors/validation',
      title: 'Validation Error', status: 400,
      detail: `${errors.length} validation error(s)`,
      correlationId, errors,
    });
  }

  if (err.code === '23505') { // PostgreSQL unique violation
    return res.status(409).json({
      type: 'https://api.example.com/errors/conflict',
      title: 'Conflict', status: 409, correlationId,
    });
  }

  logger.error({ err, correlationId, stack: err.stack });
  Sentry.captureException(err, { extra: { correlationId } });

  const isProd = process.env.NODE_ENV === 'production';
  res.status(500).json({
    type: 'https://api.example.com/errors/internal',
    title: 'Internal Server Error', status: 500,
    detail: isProd ? 'An unexpected error occurred' : err.message,
    correlationId, ...(isProd ? {} : { stack: err.stack }),
  });
}

app.use(errorHandler);

Usage in Route Handlers

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

app.post('/users', async (req, res) => {
  const parsed = CreateUserSchema.safeParse(req.body);
  if (!parsed.success) {
    throw new ValidationError(parsed.error.issues.map(i => ({
      field: i.path.join('.'), message: i.message, code: i.code,
    })));
  }
  const existing = await db.users.findByEmail(parsed.data.email);
  if (existing) throw new ConflictError('email', parsed.data.email);
  const user = await db.users.create(parsed.data);
  res.status(201).json(user);
});

curl: Error Responses

# 404
curl -i http://localhost:3000/users/nonexistent
# {"type":"...not-found","title":"Not Found","status":404,
#  "detail":"User 'nonexistent' not found","correlationId":"req_abc123"}

# 400 validation
curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" -d '{"name":"","email":"bad"}'
# {"type":"...validation","title":"Validation Error","status":400,
#  "errors":[{"field":"name","message":"Too short"},{"field":"email","message":"Invalid email"}]}

# 429 rate limit
curl -i http://localhost:3000/auth/login
# Retry-After: 45
# {"type":"...rate-limit","detail":"Rate limit exceeded","retryAfter":45}

FastAPI Error Handling (Python)

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

app = FastAPI()

class APIError(Exception):
    def __init__(self, status, error_type, title, detail):
        self.status = status
        self.error_type = error_type
        self.title = title
        self.detail = detail

@app.exception_handler(APIError)
async def api_error_handler(request: Request, exc: APIError):
    return JSONResponse(status_code=exc.status, content={
        "type": f"https://api.example.com/errors/{exc.error_type}",
        "title": exc.title, "status": exc.status,
        "detail": exc.detail, "instance": str(request.url.path),
    })

@app.get("/users/{user_id}")
async def get_user(user_id: str):
    user = await db.users.find(user_id)
    if not user:
        raise APIError(404, "not-found", "Not Found", f"User '{user_id}' not found")
    return user

Process-Level Safety Nets

process.on('unhandledRejection', (reason) => {
  logger.error('Unhandled rejection', { reason });
  Sentry.captureException(reason);
});

process.on('uncaughtException', (error) => {
  logger.fatal('Uncaught exception', { error });
  Sentry.captureException(error);
  process.exit(1);
});

Tons of Skills by Intent Solutions | jeremylongshore.com

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts2mo3 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    The skill provides secure templates and instructions for standardized API error handling. It emphasizes security best practices, such as preventing information leakage (stack traces) in production, sanitizing input, and using industry-standard tools like Sentry for error monitoring.

  • Socket2mo

    No alerts

  • Snyk2mo

    Risk: LOW · No issues

Signed by skilld at 820dfc8. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated last month
What it can do
Reads files Edits files Runs commands
version
1.25.0
author
Jeremy Longshore <jeremy@intentsolutions.io>
tags
[
  "api",
  "handling-api"
]
All 6 allowed tools
ReadWriteEditGrepGlobBash(api:error-*)
Other metadata
compatibility
Designed for Claude Code

README badge

README badge for jeremylongshore/tons-of-skills-marketplace/handling-api-errors