Implements error handling patterns, structured logging, retry strategies, circuit breakers, and graceful degradation. Use when designing error handling, setting up logging, implementing retries, adding error tracking, or when asked about error boundaries, log aggregation, alerting, or resilience patterns.
Installer avec Codex ou Claude Copiez ce prompt, collez-le dans Codex, Claude ou un autre assistant, puis laissez-le vérifier la page du skill et l'installer pour vous.
Une commande directe contourne le prompt de vérification. Examinez la source avant de l'exécuter.
Implements error handling patterns, structured logging, retry strategies, circuit breakers, and graceful degradation. Use when designing error handling, setting up logging, implementing retries, adding error tracking, or when asked about error boundaries, log aggregation, alerting, or resilience patterns.
// Middleware to propagate correlation ID across requestsimport { randomUUID } from"crypto";
import { AsyncLocalStorage } from"async_hooks";
const asyncStorage = newAsyncLocalStorage<{ correlationId: string }>();
app.use((req, res, next) => {
const correlationId =
(req.headers["x-correlation-id"] asstring) || randomUUID();
res.setHeader("x-correlation-id", correlationId);
asyncStorage.run({ correlationId }, () =>next());
});
// Logger automatically includes correlation IDfunctiongetLogger() {
const store = asyncStorage.getStore();
return logger.child({ correlationId: store?.correlationId });
}
// Usage in any handler or serviceconst log = getLogger();
log.info({ event: "payment_processed", amount: 50 });
// Output includes correlationId automatically
Log Levels Guide
TRACE: Extremely detailed (loop iterations, variable values) -- dev only
DEBUG: Diagnostic info (function entry/exit, state changes) -- dev/staging
INFO: Normal operations (request handled, job completed) -- all envs
WARN: Unexpected but recoverable (retry succeeded, fallback used)
ERROR: Operation failed (unhandled exception, service down)
FATAL: Application cannot continue (missing config, DB unreachable)
Production default: INFO
Never log: passwords, tokens, PII, credit cards, full request bodies
// Graceful degradation: serve stale data when service is downasyncfunctiongetProductRecommendations(userId: string) {
try {
returnawait recommendationService.get(userId);
} catch (error) {
logger.warn("Recommendation service unavailable, using fallback", {
userId,
error: error.message,
});
returngetCachedRecommendations(userId) || getDefaultRecommendations();
}
}
// Map internal errors to user-friendly messagesconstUSER_MESSAGES: Record<string, string> = {
VALIDATION_ERROR: "Please check your input and try again.",
NOT_FOUND: "The requested resource could not be found.",
RATE_LIMITED: "Too many requests. Please wait a moment.",
PAYMENT_FAILED: "Payment could not be processed. Please try another method.",
INTERNAL_ERROR: "Something went wrong. Please try again later.",
};
functiontoUserResponse(error: AppError) {
return {
error: {
code: error.code,
message: USER_MESSAGES[error.code] || USER_MESSAGES["INTERNAL_ERROR"],
},
};
}
// WRONG: Exposing internal details to users
res.status(500).json({
error: 'QueryFailedError: relation "users" does not exist',
stack: error.stack,
});
// CORRECT: Generic message to user, full details in logs
logger.error("Database query failed", {
error: error.message,
stack: error.stack,
query,
});
res.status(500).json(toUserResponse(newAppError("DB error", 500)));
Common Anti-Patterns Summary
AVOID DO INSTEAD
-------------------------------------------------------------------
Empty catch blocks Log and handle or re-throw
Bare `except:` in Python Catch specific exceptions
console.log for production Structured logger (pino, winston)
Logging passwords/tokens Redact sensitive fields
Retry without backoff Exponential backoff with jitter
Retry on all errors Only retry transient/network errors
No circuit breaker Circuit breaker for external calls
Exposing stack traces to users Generic user messages, detailed logs
No correlation IDs Propagate correlation ID across services
One giant try/catch Granular error handling per operation
Logging inside tight loops Log summaries/aggregates
No error boundaries in React Wrap independent sections separately