用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/tools-only/X-Skills --skill implement-error-handling命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
正在显示 SKILL.md
| name | implement-error-handling |
| description | Implement standardized API error handling |
| shortcut | erro |
Create standardized, production-ready error handling middleware with proper HTTP status codes, consistent error formats, and comprehensive logging. This command generates custom error classes, middleware, and error recovery strategies for Node.js, Python, and other backend frameworks.
Why standardized error handling matters:
Alternatives considered:
This approach balances: Developer experience, security, debugging, and API consistency.
Use this command when:
Don't use when:
Generate Custom Error Classes
Build Error Middleware
Configure Environment-Specific Behavior
Integrate Logging
Add Error Recovery
// errors/AppError.js
class AppError extends Error {
constructor(message, statusCode, errorCode = null) {
super(message);
this.statusCode = statusCode;
this.errorCode = errorCode;
this.isOperational = true;
this.timestamp = new Date().toISOString();
Error.captureStackTrace(this, this.constructor);
}
}
class ValidationError extends AppError {
constructor(message, errors = []) {
super(message, 400, 'VALIDATION_ERROR');
this.errors = errors;
}
}
class NotFoundError extends AppError {
constructor(resource) {
super(`${resource} not found`, 404, 'NOT_FOUND');
this. = resource;
}
}
{
() {
(message, , );
}
}
{
() {
(message, , );
}
}
. = { , , , , };
logger = ();
= () => {
statusCode = err. || ;
message = err. || ;
logger.({
: err.,
statusCode,
: err.,
: err.,
: req.,
: req.,
: req.,
: req.?.,
: req.
});
(process.. === && !err.) {
message = ;
statusCode = ;
}
res.(statusCode).({
: {
message,
: err.,
statusCode,
: err. || ().(),
: req.,
...(process.. === && { : err. }),
...(err. && { : err. })
}
});
};
. = errorHandler;
# errors/exceptions.py
from typing import Optional, Any, Dict
from fastapi import HTTPException
from datetime import datetime
class AppError(HTTPException):
def __init__(
self,
status_code: int,
message: str,
error_code: Optional[str] = None,
details: Optional[Dict[str, Any]] = None
):
self.status_code = status_code
self.message = message
self.error_code = error_code
self.details = details or {}
self.timestamp = datetime.utcnow().isoformat()
super().__init__(status_code=status_code, detail=message)
class ValidationError(AppError):
def __init__(self, message: str, errors: list = None):
super().__init__(
status_code=400,
message=message,
error_code="VALIDATION_ERROR",
details={"errors": errors or []}
)
():
():
().__init__(
status_code=,
message=,
error_code=,
details={: resource}
)
():
():
().__init__(
status_code=,
message=message,
error_code=
)
fastapi FastAPI, Request
fastapi.responses JSONResponse
logging
app = FastAPI()
logger = logging.getLogger(__name__)
():
logger.error(
,
extra={
: exc.status_code,
: exc.error_code,
: request.url.path,
: request.method
}
)
JSONResponse(
status_code=exc.status_code,
content={
: {
: exc.message,
: exc.error_code,
: exc.status_code,
: exc.timestamp,
: (request.url.path),
**exc.details
}
}
)
():
logger.exception(, exc_info=exc)
JSONResponse(
status_code=,
content={
: {
: ,
: ,
: ,
: datetime.utcnow().isoformat()
}
}
)
const { ValidationError } = require('./errors/AppError');
const { body, validationResult } = require('express-validator');
router.post('/users',
[
body('email').isEmail().normalizeEmail(),
body('password').isLength({ min: 8 }),
body('name').trim().notEmpty()
],
async (req, res, next) => {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
throw new ValidationError('Validation failed', errors.array());
}
const user = await createUser(req.body);
res.status(201).json(user);
} catch (error) {
next(error);
}
}
);
// Response for invalid input:
// {
// "error": {
// "message": "Validation failed",
// "code": "VALIDATION_ERROR",
// "statusCode": 400,
from fastapi import APIRouter
from errors.exceptions import NotFoundError
router = APIRouter()
@router.get("/users/{user_id}")
async def get_user(user_id: int):
user = await db.get_user(user_id)
if not user:
raise NotFoundError("User")
return user
# Response:
# {
# "error": {
# "message": "User not found",
# "code": "NOT_FOUND",
# "statusCode": 404,
# "timestamp": "2025-10-11T12:00:00.000Z",
# "path": "/users/123",
# "details": {
# "resource": "User"
# }
# }
# }
const { AppError } = require('./errors/AppError');
const retry = require('async-retry');
async function callExternalAPI(endpoint) {
return retry(async (bail, attempt) => {
try {
const response = await fetch(endpoint);
if (!response.ok) {
// Don't retry client errors
if (response.status >= 400 && response.status < 500) {
bail(new AppError('External API error', response.status));
return;
}
// Retry server errors
throw new Error(`API returned ${response.status}`);
}
return response.json();
} catch (error) {
console.log(`Attempt ${attempt} failed: ${error.message}`);
throw error;
}
}, {
retries: 3,
minTimeout: ,
:
});
}
Common issues and solutions:
Problem: Errors logged multiple times
Problem: Stack traces visible in production
NODE_ENV=production is set, check conditional logicProblem: Lost error context (request ID, user info)
Problem: Async errors not caught
Problem: Database connection errors crashing app
process.on('unhandledRejection', (reason, promise) => {
logger.error('Unhandled Rejection', { reason, promise });
// Optionally exit: process.exit(1);
});
process.on('uncaughtException', (error) => {
logger.error('Uncaught Exception', { error });
process.exit(1); // Must exit, app is in undefined state
});
const errorHandlerOptions = {
// Include stack traces
showStack: process.env.NODE_ENV === 'development',
// Log level for different error types
logLevel: {
operational: 'error',
programmer: 'critical'
},
// Send errors to monitoring service
reportToMonitoring: process.env.NODE_ENV === 'production',
// Sanitize sensitive fields
sanitizeFields: ['password', 'ssn', 'creditCard'],
// Custom error formatters
formatters: {
json: (err) => ({ error: err.toJSON() }),
xml: (err) => convertToXML(err)
}
};
DO:
DON'T:
TIPS:
INSUFFICIENT_FUNDS, RATE_LIMIT_EXCEEDED)/validate-api-responses - Validate API responses match schemas/setup-logging - Configure structured logging for errors/scan-api-security - Scan for security vulnerabilities in error handling/create-monitoring - Set up error monitoring dashboards/generate-rest-api - Generate REST API with built-in error handlingOptimization strategies:
// Disable stack traces in production for performance
if (process.env.NODE_ENV === 'production') {
Error.stackTraceLimit = 0;
}
// Use structured logging with async writes
const logger = winston.createLogger({
transports: [
new winston.transports.File({
filename: 'error.log',
level: 'error'
})
]
});
Security checklist:
// BAD: Exposes internal structure
throw new Error(`User ${userId} not found in users table`);
// GOOD: Generic message
throw new NotFoundError('User');
// BAD: Reveals existence
if (!user) throw new Error('User not found');
if (password !== user.password) throw new Error('Wrong password');
// GOOD: Generic auth failure
if (!user || password !== user.password) {
throw new UnauthorizedError('Invalid credentials');
}
Error handler not catching errors:
next(error) or use express-async-errorsErrors not logged:
Production errors too verbose:
Error monitoring not working:
基于 SOC 职业分类