api-error-handling
FreeNo executable scriptsNot checkedImplement comprehensive API error handling with standardized error responses, logging, monitoring, and user-friendly messages. Use when building resilient…
by diegosouzapw★ 68 GitHub starsAbout 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
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
Allowed tools
Tools this skill is permitted to call.
No restriction — this skill can use any tool.
Bundled files
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
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
by Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
by Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
by Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
by Anthropic