analyzing-projects
Analyzes codebases to understand structure, tech stack, patterns, and conventions. Use when…
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,
$ npx -y skills add CloudAI-X/claude-workflow-v2 --skill error-handling --agent claude-codeHow it fires
How this skill gets triggered: by you, by Claude, or both.
/error-handlingContext preview
The summary Claude sees to decide when to auto-load this skill.
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,
name: error-handling description: 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.
Copy this checklist and track progress:
Error Handling Progress: - [ ] Step 1: Define error taxonomy (categories and severity) - [ ] Step 2: Implement error handling by layer - [ ] Step 3: Set up structured logging - [ ] Step 4: Add retry and circuit breaker patterns - [ ] Step 5: Configure error tracking service - [ ] Step 6: Define user-facing error messages - [ ] Step 7: Validate against anti-patterns checklist
// Custom error hierarchy
class AppError extends Error {
constructor(
message: string,
public statusCode: number = 500,
public code: string = "INTERNAL_ERROR",
public isOperational: boolean = true,
) {
super(message);
this.name = this.constructor.name;
}
}
class NotFoundError extends AppError {
constructor(resource: string, id: string) {
super(`${resource} with id ${id} not found`, 404, "NOT_FOUND");
}
}
class ValidationError extends AppError {
constructor(public errors: Record<string, string[]>) {
super("Validation failed", 400, "VALIDATION_ERROR");
}
}
// WRONG: Swallowing errors silently
try {
await saveUser(data);
} catch (e) {
// nothing here -- bug hides forever
}
// WRONG: Catching and re-throwing without context
try {
await saveUser(data);
} catch (e) {
throw e; // pointless try/catch
}
// CORRECT: Add context, handle or propagate
try {
await saveUser(data);
} catch (error) {
if (error instanceof ValidationError) {
return res.status(400).json({ errors: error.errors });
}
logger.error({ err: error, userId: data.id }, "Failed to save user");
throw new AppError("Unable to save user", 500, "USER_SAVE_FAILED");
}// Centralized error handler middleware (must have 4 params)
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
if (err instanceof AppError) {
logger.warn(
{ code: err.code, statusCode: err.statusCode, path: req.path },
"Operational error",
);
return res.status(err.statusCode).json({
error: { code: err.code, message: err.message },
});
}
// Unexpected errors -- these are bugs
logger.error({ err, path: req.path }, "Unexpected error");
res.status(500).json({
error: { code: "INTERNAL_ERROR", message: "An unexpected error occurred" },
});
});# Custom exception hierarchy
class AppError(Exception):
def __init__(self, message: str, code: str = "INTERNAL_ERROR", status: int = 500):
self.message = message
self.code = code
self.status = status
super().__init__(message)
class NotFoundError(AppError):
def __init__(self, resource: str, id: str):
super().__init__(f"{resource} {id} not found", "NOT_FOUND", 404)
class ValidationError(AppError):
def __init__(self, errors: dict[str, list[str]]):
self.errors = errors
super().__init__("Validation failed", "VALIDATION_ERROR", 400)
# WRONG: Bare except
try:
result = process(data)
except: # catches SystemExit, KeyboardInterrupt too!
pass
# CORRECT: Specific exceptions, proper logging
try:
result = process(data)
except ValidationError as e:
logger.warning("Validation failed", extra={"errors": e.errors})
raise
except DatabaseError as e:
logger.error("Database error during processing", exc_info=True)
raise AppError("Processing failed", "PROCESS_FAILED") from e// Define sentinel errors and custom types
var (
ErrNotFound = errors.New("resource not found")
ErrUnauthorized = errors.New("unauthorized")
)
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("validation: %s - %s", e.Field, e.Message)
}
// WRONG: Ignoring errors
data, _ := json.Marshal(user) // error silently dropped
// WRONG: Only returning error string
if err != nil {
return fmt.Errorf("failed: %s", err.Error()) // loses error chain
}
// CORRECT: Wrap errors with context
if err != nil {
return fmt.Errorf("saving user %s: %w", user.ID, err) // %w preserves chain
}
// CORRECT: Check error types
if errors.Is(err, ErrNotFound) {
http.Error(w, "Not found", http.StatusNotFound)
return
}
var valErr *ValidationError
if errors.As(err, &valErr) {
http.Error(w, valErr.Error(), http.StatusBadRequest)
return
}// WRONG: Unstructured string logs
console.log(`User ${userId} created order ${orderId} at ${new Date()}`);
// Impossible to parse, filter, or aggregate
// CORRECT: Structured JSON logs
import pino from "pino";
const logger = pino({
level: process.env.LOG_LEVEL || "info",
formatters: {
level: (label) => ({ level: label }),
},
redact: ["req.headers.authorization", "password", "ssn"],
});
logger.info({
event: "order_created",
userId: "123",
orderId: "456",
amount: 99.99,
currency: "USD",
});
// Output: {"level":"info","event":"order_created","userId":"123","orderId":"456",...}// Middleware to propagate correlation ID across requests
import { randomUUID } from "crypto";
import { AsyncLocalStorage } from "async_hooks";
const asyncStorage = new AsyncLocalStorage<{ correlationId: string }>();
app.use((req, res,A universal Claude Code workflow plugin with specialized agents, skills, hooks, and mode commands for any software project. Compatible with skills.sh — works with Claude Code, Cursor, Codex, and 35+ AI agents.
Repo: CloudAI-X/claude-workflow-v2
Analyzes codebases to understand structure, tech stack, patterns, and conventions. Use when…
Convex backend development guidelines. Use when writing Convex functions, schemas, queries,…
Designs database schemas, indexing strategies, query optimization, and migration patterns for…
Designs REST and GraphQL APIs including endpoints, error handling, versioning, and…
Designs software architecture and selects appropriate patterns for projects. Use when…
Designs and implements testing strategies for any codebase. Use when adding tests, improving…