Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
직접 명령은 검토 Prompt를 거치지 않습니다. 실행하기 전에 소스를 확인하세요.
npx skills add https://github.com/tools-only/X-Skills --skill implement-error-handling명령은 한 줄로 유지됩니다. 복사하기 전에 가로로 스크롤해 전체 내용을 확인하세요.
로컬 사본을 원하시나요? SkillsMP에서 현재 제공할 수 있는 파일을 다운로드하세요.
SKILL.md 표시 중
SOC 직업 분류 기준
| 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: