api-error-handling
Implement comprehensive API error handling with standardized error responses, logging, monitoring, and user-friendly messages. Use when building resilient…
от diegosouzapw★ 68 звёзд на GitHub
Установить api-error-handling в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
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
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- metadata.json
FAQ
Что делает скилл api-error-handling?
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.
Как установить скилл api-error-handling?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл api-error-handling запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
AnthropicGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
claude-api
AnthropicReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
algorithmic-art
AnthropicCreating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
mcp-integration
AnthropicThis 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…