[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6CD0589CDH5DHX52C61M0F1":3,"skill-same:01M6CD0589CDH5DHX52C61M0F1":65},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":47,"repositoryHtmlUrl":48,"repositoryHomepageUrl":6,"ownerHtmlUrl":49,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":50,"install":51,"resources":64},"01M6CD0589CDH5DHX52C61M0F1","error-handling-patterns",null,"Master error handling patterns across languages including exceptions, Result types, error propagation, and graceful degradation to build resilient applications. Use when implementing error handling, designing APIs, or improving application reliability.","cercova-studios\u002F10x-swe","cercova-studios","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F217108198?v=4","01M6CCYGHXTH80N3BXRW6KESTE","Cercova Studios","01M6CCYGPADH5MJDR0VNNR775C",1,"MIT","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Ferror-handling-patterns\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"error handling patterns","patterns","error handling","error","propagation","Error Propagation","when","graceful degradation","result","implementing","types","designing apis","degradation","across","application","build","master","reliability","use","applications","2026-11-10 10:12:30",false,"---\nname: error-handling-patterns\ndescription: Master error handling patterns across languages including exceptions, Result types, error propagation, and graceful degradation to build resilient applications. Use when implementing error handling, designing APIs, or improving application reliability.\n---\n\n# Error Handling Patterns\n\nBuild resilient applications with robust error handling strategies that gracefully handle failures and provide excellent debugging experiences.\n\n## When to Use This Skill\n\n- Implementing error handling in new features\n- Designing error-resilient APIs\n- Debugging production issues\n- Improving application reliability\n- Creating better error messages for users and developers\n- Implementing retry and circuit breaker patterns\n- Handling async\u002Fconcurrent errors\n- Building fault-tolerant distributed systems\n\n## Core Concepts\n\n### 1. Error Handling Philosophies\n\n**Exceptions vs Result Types:**\n\n- **Exceptions**: Traditional try-catch, disrupts control flow\n- **Result Types**: Explicit success\u002Ffailure, functional approach\n- **Error Codes**: C-style, requires discipline\n- **Option\u002FMaybe Types**: For nullable values\n\n**When to Use Each:**\n\n- Exceptions: Unexpected errors, exceptional conditions\n- Result Types: Expected errors, validation failures\n- Panics\u002FCrashes: Unrecoverable errors, programming bugs\n\n### 2. Error Categories\n\n**Recoverable Errors:**\n\n- Network timeouts\n- Missing files\n- Invalid user input\n- API rate limits\n\n**Unrecoverable Errors:**\n\n- Out of memory\n- Stack overflow\n- Programming bugs (null pointer, etc.)\n\n## Language-Specific Patterns\n\n### Python Error Handling\n\n**Custom Exception Hierarchy:**\n\n```python\nclass ApplicationError(Exception):\n    \"\"\"Base exception for all application errors.\"\"\"\n    def __init__(self, message: str, code: str = None, details: dict = None):\n        super().__init__(message)\n        self.code = code\n        self.details = details or {}\n        self.timestamp = datetime.utcnow()\n\nclass ValidationError(ApplicationError):\n    \"\"\"Raised when validation fails.\"\"\"\n    pass\n\nclass NotFoundError(ApplicationError):\n    \"\"\"Raised when resource not found.\"\"\"\n    pass\n\nclass ExternalServiceError(ApplicationError):\n    \"\"\"Raised when external service fails.\"\"\"\n    def __init__(self, message: str, service: str, **kwargs):\n        super().__init__(message, **kwargs)\n        self.service = service\n\n# Usage\ndef get_user(user_id: str) -> User:\n    user = db.query(User).filter_by(id=user_id).first()\n    if not user:\n        raise NotFoundError(\n            f\"User not found\",\n            code=\"USER_NOT_FOUND\",\n            details={\"user_id\": user_id}\n        )\n    return user\n```\n\n**Context Managers for Cleanup:**\n\n```python\nfrom contextlib import contextmanager\n\n@contextmanager\ndef database_transaction(session):\n    \"\"\"Ensure transaction is committed or rolled back.\"\"\"\n    try:\n        yield session\n        session.commit()\n    except Exception as e:\n        session.rollback()\n        raise\n    finally:\n        session.close()\n\n# Usage\nwith database_transaction(db.session) as session:\n    user = User(name=\"Alice\")\n    session.add(user)\n    # Automatic commit or rollback\n```\n\n**Retry with Exponential Backoff:**\n\n```python\nimport time\nfrom functools import wraps\nfrom typing import TypeVar, Callable\n\nT = TypeVar('T')\n\ndef retry(\n    max_attempts: int = 3,\n    backoff_factor: float = 2.0,\n    exceptions: tuple = (Exception,)\n):\n    \"\"\"Retry decorator with exponential backoff.\"\"\"\n    def decorator(func: Callable[..., T]) -> Callable[..., T]:\n        @wraps(func)\n        def wrapper(*args, **kwargs) -> T:\n            last_exception = None\n            for attempt in range(max_attempts):\n                try:\n                    return func(*args, **kwargs)\n                except exceptions as e:\n                    last_exception = e\n                    if attempt \u003C max_attempts - 1:\n                        sleep_time = backoff_factor ** attempt\n                        time.sleep(sleep_time)\n                        continue\n                    raise\n            raise last_exception\n        return wrapper\n    return decorator\n\n# Usage\n@retry(max_attempts=3, exceptions=(NetworkError,))\ndef fetch_data(url: str) -> dict:\n    response = requests.get(url, timeout=5)\n    response.raise_for_status()\n    return response.json()\n```\n\n### TypeScript\u002FJavaScript Error Handling\n\n**Custom Error Classes:**\n\n```typescript\n\u002F\u002F Custom error classes\nclass ApplicationError extends Error {\n  constructor(\n    message: string,\n    public code: string,\n    public statusCode: number = 500,\n    public details?: Record\u003Cstring, any>,\n  ) {\n    super(message);\n    this.name = this.constructor.name;\n    Error.captureStackTrace(this, this.constructor);\n  }\n}\n\nclass ValidationError extends ApplicationError {\n  constructor(message: string, details?: Record\u003Cstring, any>) {\n    super(message, \"VALIDATION_ERROR\", 400, details);\n  }\n}\n\nclass NotFoundError extends ApplicationError {\n  constructor(resource: string, id: string) {\n    super(`${resource} not found`, \"NOT_FOUND\", 404, { resource, id });\n  }\n}\n\n\u002F\u002F Usage\nfunction getUser(id: string): User {\n  const user = users.find((u) => u.id === id);\n  if (!user) {\n    throw new NotFoundError(\"User\", id);\n  }\n  return user;\n}\n```\n\n**Result Type Pattern:**\n\n```typescript\n\u002F\u002F Result type for explicit error handling\ntype Result\u003CT, E = Error> = { ok: true; value: T } | { ok: false; error: E };\n\n\u002F\u002F Helper functions\nfunction Ok\u003CT>(value: T): Result\u003CT, never> {\n  return { ok: true, value };\n}\n\nfunction Err\u003CE>(error: E): Result\u003Cnever, E> {\n  return { ok: false, error };\n}\n\n\u002F\u002F Usage\nfunction parseJSON\u003CT>(json: string): Result\u003CT, SyntaxError> {\n  try {\n    const value = JSON.parse(json) as T;\n    return Ok(value);\n  } catch (error) {\n    return Err(error as SyntaxError);\n  }\n}\n\n\u002F\u002F Consuming Result\nconst result = parseJSON\u003CUser>(userJson);\nif (result.ok) {\n  console.log(result.value.name);\n} else {\n  console.error(\"Parse failed:\", result.error.message);\n}\n\n\u002F\u002F Chaining Results\nfunction chain\u003CT, U, E>(\n  result: Result\u003CT, E>,\n  fn: (value: T) => Result\u003CU, E>,\n): Result\u003CU, E> {\n  return result.ok ? fn(result.value) : result;\n}\n```\n\n**Async Error Handling:**\n\n```typescript\n\u002F\u002F Async\u002Fawait with proper error handling\nasync function fetchUserOrders(userId: string): Promise\u003COrder[]> {\n  try {\n    const user = await getUser(userId);\n    const orders = await getOrders(user.id);\n    return orders;\n  } catch (error) {\n    if (error instanceof NotFoundError) {\n      return []; \u002F\u002F Return empty array for not found\n    }\n    if (error instanceof NetworkError) {\n      \u002F\u002F Retry logic\n      return retryFetchOrders(userId);\n    }\n    \u002F\u002F Re-throw unexpected errors\n    throw error;\n  }\n}\n\n\u002F\u002F Promise error handling\nfunction fetchData(url: string): Promise\u003CData> {\n  return fetch(url)\n    .then((response) => {\n      if (!response.ok) {\n        throw new NetworkError(`HTTP ${response.status}`);\n      }\n      return response.json();\n    })\n    .catch((error) => {\n      console.error(\"Fetch failed:\", error);\n      throw error;\n    });\n}\n```\n\n### Rust Error Handling\n\n**Result and Option Types:**\n\n```rust\nuse std::fs::File;\nuse std::io::{self, Read};\n\n\u002F\u002F Result type for operations that can fail\nfn read_file(path: &str) -> Result\u003CString, io::Error> {\n    let mut file = File::open(path)?;  \u002F\u002F ? operator propagates errors\n    let mut contents = String::new();\n    file.read_to_string(&mut contents)?;\n    Ok(contents)\n}\n\n\u002F\u002F Custom error types\n#[derive(Debug)]\nenum AppError {\n    Io(io::Error),\n    Parse(std::num::ParseIntError),\n    NotFound(String),\n    Validation(String),\n}\n\nimpl From\u003Cio::Error> for AppError {\n    fn from(error: io::Error) -> Self {\n        AppError::Io(error)\n    }\n}\n\n\u002F\u002F Using custom error type\nfn read_number_from_file(path: &str) -> Result\u003Ci32, AppError> {\n    let contents = read_file(path)?;  \u002F\u002F Auto-converts io::Error\n    let number = contents.trim().parse()\n        .map_err(AppError::Parse)?;   \u002F\u002F Explicitly convert ParseIntError\n    Ok(number)\n}\n\n\u002F\u002F Option for nullable values\nfn find_user(id: &str) -> Option\u003CUser> {\n    users.iter().find(|u| u.id == id).cloned()\n}\n\n\u002F\u002F Combining Option and Result\nfn get_user_age(id: &str) -> Result\u003Cu32, AppError> {\n    find_user(id)\n        .ok_or_else(|| AppError::NotFound(id.to_string()))\n        .map(|user| user.age)\n}\n```\n\n### Go Error Handling\n\n**Explicit Error Returns:**\n\n```go\n\u002F\u002F Basic error handling\nfunc getUser(id string) (*User, error) {\n    user, err := db.QueryUser(id)\n    if err != nil {\n        return nil, fmt.Errorf(\"failed to query user: %w\", err)\n    }\n    if user == nil {\n        return nil, errors.New(\"user not found\")\n    }\n    return user, nil\n}\n\n\u002F\u002F Custom error types\ntype ValidationError struct {\n    Field   string\n    Message string\n}\n\nfunc (e *ValidationError) Error() string {\n    return fmt.Sprintf(\"validation failed for %s: %s\", e.Field, e.Message)\n}\n\n\u002F\u002F Sentinel errors for comparison\nvar (\n    ErrNotFound     = errors.New(\"not found\")\n    ErrUnauthorized = errors.New(\"unauthorized\")\n    ErrInvalidInput = errors.New(\"invalid input\")\n)\n\n\u002F\u002F Error checking\nuser, err := getUser(\"123\")\nif err != nil {\n    if errors.Is(err, ErrNotFound) {\n        \u002F\u002F Handle not found\n    } else {\n        \u002F\u002F Handle other errors\n    }\n}\n\n\u002F\u002F Error wrapping and unwrapping\nfunc processUser(id string) error {\n    user, err := getUser(id)\n    if err != nil {\n        return fmt.Errorf(\"process user failed: %w\", err)\n    }\n    \u002F\u002F Process user\n    return nil\n}\n\n\u002F\u002F Unwrap errors\nerr := processUser(\"123\")\nif err != nil {\n    var valErr *ValidationError\n    if errors.As(err, &valErr) {\n        fmt.Printf(\"Validation error: %s\\n\", valErr.Field)\n    }\n}\n```\n\n## Universal Patterns\n\n### Pattern 1: Circuit Breaker\n\nPrevent cascading failures in distributed systems.\n\n```python\nfrom enum import Enum\nfrom datetime import datetime, timedelta\nfrom typing import Callable, TypeVar\n\nT = TypeVar('T')\n\nclass CircuitState(Enum):\n    CLOSED = \"closed\"       # Normal operation\n    OPEN = \"open\"          # Failing, reject requests\n    HALF_OPEN = \"half_open\"  # Testing if recovered\n\nclass CircuitBreaker:\n    def __init__(\n        self,\n        failure_threshold: int = 5,\n        timeout: timedelta = timedelta(seconds=60),\n        success_threshold: int = 2\n    ):\n        self.failure_threshold = failure_threshold\n        self.timeout = timeout\n        self.success_threshold = success_threshold\n        self.failure_count = 0\n        self.success_count = 0\n        self.state = CircuitState.CLOSED\n        self.last_failure_time = None\n\n    def call(self, func: Callable[[], T]) -> T:\n        if self.state == CircuitState.OPEN:\n            if datetime.now() - self.last_failure_time > self.timeout:\n                self.state = CircuitState.HALF_OPEN\n                self.success_count = 0\n            else:\n                raise Exception(\"Circuit breaker is OPEN\")\n\n        try:\n            result = func()\n            self.on_success()\n            return result\n        except Exception as e:\n            self.on_failure()\n            raise\n\n    def on_success(self):\n        self.failure_count = 0\n        if self.state == CircuitState.HALF_OPEN:\n            self.success_count += 1\n            if self.success_count >= self.success_threshold:\n                self.state = CircuitState.CLOSED\n                self.success_count = 0\n\n    def on_failure(self):\n        self.failure_count += 1\n        self.last_failure_time = datetime.now()\n        if self.failure_count >= self.failure_threshold:\n            self.state = CircuitState.OPEN\n\n# Usage\ncircuit_breaker = CircuitBreaker()\n\ndef fetch_data():\n    return circuit_breaker.call(lambda: external_api.get_data())\n```\n\n### Pattern 2: Error Aggregation\n\nCollect multiple errors instead of failing on first error.\n\n```typescript\nclass ErrorCollector {\n  private errors: Error[] = [];\n\n  add(error: Error): void {\n    this.errors.push(error);\n  }\n\n  hasErrors(): boolean {\n    return this.errors.length > 0;\n  }\n\n  getErrors(): Error[] {\n    return [...this.errors];\n  }\n\n  throw(): never {\n    if (this.errors.length === 1) {\n      throw this.errors[0];\n    }\n    throw new AggregateError(\n      this.errors,\n      `${this.errors.length} errors occurred`,\n    );\n  }\n}\n\n\u002F\u002F Usage: Validate multiple fields\nfunction validateUser(data: any): User {\n  const errors = new ErrorCollector();\n\n  if (!data.email) {\n    errors.add(new ValidationError(\"Email is required\"));\n  } else if (!isValidEmail(data.email)) {\n    errors.add(new ValidationError(\"Email is invalid\"));\n  }\n\n  if (!data.name || data.name.length \u003C 2) {\n    errors.add(new ValidationError(\"Name must be at least 2 characters\"));\n  }\n\n  if (!data.age || data.age \u003C 18) {\n    errors.add(new ValidationError(\"Age must be 18 or older\"));\n  }\n\n  if (errors.hasErrors()) {\n    errors.throw();\n  }\n\n  return data as User;\n}\n```\n\n### Pattern 3: Graceful Degradation\n\nProvide fallback functionality when errors occur.\n\n```python\nfrom typing import Optional, Callable, TypeVar\n\nT = TypeVar('T')\n\ndef with_fallback(\n    primary: Callable[[], T],\n    fallback: Callable[[], T],\n    log_error: bool = True\n) -> T:\n    \"\"\"Try primary function, fall back to fallback on error.\"\"\"\n    try:\n        return primary()\n    except Exception as e:\n        if log_error:\n            logger.error(f\"Primary function failed: {e}\")\n        return fallback()\n\n# Usage\ndef get_user_profile(user_id: str) -> UserProfile:\n    return with_fallback(\n        primary=lambda: fetch_from_cache(user_id),\n        fallback=lambda: fetch_from_database(user_id)\n    )\n\n# Multiple fallbacks\ndef get_exchange_rate(currency: str) -> float:\n    return (\n        try_function(lambda: api_provider_1.get_rate(currency))\n        or try_function(lambda: api_provider_2.get_rate(currency))\n        or try_function(lambda: cache.get_rate(currency))\n        or DEFAULT_RATE\n    )\n\ndef try_function(func: Callable[[], Optional[T]]) -> Optional[T]:\n    try:\n        return func()\n    except Exception:\n        return None\n```\n\n## Best Practices\n\n1. **Fail Fast**: Validate input early, fail quickly\n2. **Preserve Context**: Include stack traces, metadata, timestamps\n3. **Meaningful Messages**: Explain what happened and how to fix it\n4. **Log Appropriately**: Error = log, expected failure = don't spam logs\n5. **Handle at Right Level**: Catch where you can meaningfully handle\n6. **Clean Up Resources**: Use try-finally, context managers, defer\n7. **Don't Swallow Errors**: Log or re-throw, don't silently ignore\n8. **Type-Safe Errors**: Use typed errors when possible\n\n```python\n# Good error handling example\ndef process_order(order_id: str) -> Order:\n    \"\"\"Process order with comprehensive error handling.\"\"\"\n    try:\n        # Validate input\n        if not order_id:\n            raise ValidationError(\"Order ID is required\")\n\n        # Fetch order\n        order = db.get_order(order_id)\n        if not order:\n            raise NotFoundError(\"Order\", order_id)\n\n        # Process payment\n        try:\n            payment_result = payment_service.charge(order.total)\n        except PaymentServiceError as e:\n            # Log and wrap external service error\n            logger.error(f\"Payment failed for order {order_id}: {e}\")\n            raise ExternalServiceError(\n                f\"Payment processing failed\",\n                service=\"payment_service\",\n                details={\"order_id\": order_id, \"amount\": order.total}\n            ) from e\n\n        # Update order\n        order.status = \"completed\"\n        order.payment_id = payment_result.id\n        db.save(order)\n\n        return order\n\n    except ApplicationError:\n        # Re-raise known application errors\n        raise\n    except Exception as e:\n        # Log unexpected errors\n        logger.exception(f\"Unexpected error processing order {order_id}\")\n        raise ApplicationError(\n            \"Order processing failed\",\n            code=\"INTERNAL_ERROR\"\n        ) from e\n```\n\n## Common Pitfalls\n\n- **Catching Too Broadly**: `except Exception` hides bugs\n- **Empty Catch Blocks**: Silently swallowing errors\n- **Logging and Re-throwing**: Creates duplicate log entries\n- **Not Cleaning Up**: Forgetting to close files, connections\n- **Poor Error Messages**: \"Error occurred\" is not helpful\n- **Returning Error Codes**: Use exceptions or Result types\n- **Ignoring Async Errors**: Unhandled promise rejections\n","# Error Handling Patterns\n\nBuild resilient applications with robust error handling strategies that gracefully handle failures and provide excellent debugging experiences.\n\n## When to Use This Skill\n\n- Implementing error handling in new features\n- Designing error-resilient APIs\n- Debugging production issues\n- Improving application reliability\n- Creating better error messages for users and developers\n- Implementing retry and circuit breaker patterns\n- Handling async\u002Fconcurrent errors\n- Building fault-tolerant distributed systems\n\n## Core Concepts\n\n### 1. Error Handling Philosophies\n\n**Exceptions vs Result Types:**\n\n- **Exceptions**: Traditional try-catch, disrupts control flow\n- **Result Types**: Explicit success\u002Ffailure, functional approach\n- **Error Codes**: C-style, requires discipline\n- **Option\u002FMaybe Types**: For nullable values\n\n**When to Use Each:**\n\n- Exceptions: Unexpected errors, exceptional conditions\n- Result Types: Expected errors, validation failures\n- Panics\u002FCrashes: Unrecoverable errors, programming bugs\n\n### 2. Error Categories\n\n**Recoverable Errors:**\n\n- Network timeouts\n- Missing files\n- Invalid user input\n- API rate limits\n\n**Unrecoverable Errors:**\n\n- Out of memory\n- Stack overflow\n- Programming bugs (null pointer, etc.)\n\n## Language-Specific Patterns\n\n### Python Error Handling\n\n**Custom Exception Hierarchy:**\n\n```python\nclass ApplicationError(Exception):\n    \"\"\"Base exception for all application errors.\"\"\"\n    def __init__(self, message: str, code: str = None, details: dict = None):\n        super().__init__(message)\n        self.code = code\n        self.details = details or {}\n        self.timestamp = datetime.utcnow()\n\nclass ValidationError(ApplicationError):\n    \"\"\"Raised when validation fails.\"\"\"\n    pass\n\nclass NotFoundError(ApplicationError):\n    \"\"\"Raised when resource not found.\"\"\"\n    pass\n\nclass ExternalServiceError(ApplicationError):\n    \"\"\"Raised when external service fails.\"\"\"\n    def __init__(self, message: str, service: str, **kwargs):\n        super().__init__(message, **kwargs)\n        self.service = service\n\n# Usage\ndef get_user(user_id: str) -> User:\n    user = db.query(User).filter_by(id=user_id).first()\n    if not user:\n        raise NotFoundError(\n            f\"User not found\",\n            code=\"USER_NOT_FOUND\",\n            details={\"user_id\": user_id}\n        )\n    return user\n```\n\n**Context Managers for Cleanup:**\n\n```python\nfrom contextlib import contextmanager\n\n@contextmanager\ndef database_transaction(session):\n    \"\"\"Ensure transaction is committed or rolled back.\"\"\"\n    try:\n        yield session\n        session.commit()\n    except Exception as e:\n        session.rollback()\n        raise\n    finally:\n        session.close()\n\n# Usage\nwith database_transaction(db.session) as session:\n    user = User(name=\"Alice\")\n    session.add(user)\n    # Automatic commit or rollback\n```\n\n**Retry with Exponential Backoff:**\n\n```python\nimport time\nfrom functools import wraps\nfrom typing import TypeVar, Callable\n\nT = TypeVar('T')\n\ndef retry(\n    max_attempts: int = 3,\n    backoff_factor: float = 2.0,\n    exceptions: tuple = (Exception,)\n):\n    \"\"\"Retry decorator with exponential backoff.\"\"\"\n    def decorator(func: Callable[..., T]) -> Callable[..., T]:\n        @wraps(func)\n        def wrapper(*args, **kwargs) -> T:\n            last_exception = None\n            for attempt in range(max_attempts):\n                try:\n                    return func(*args, **kwargs)\n                except exceptions as e:\n                    last_exception = e\n                    if attempt \u003C max_attempts - 1:\n                        sleep_time = backoff_factor ** attempt\n                        time.sleep(sleep_time)\n                        continue\n                    raise\n            raise last_exception\n        return wrapper\n    return decorator\n\n# Usage\n@retry(max_attempts=3, exceptions=(NetworkError,))\ndef fetch_data(url: str) -> dict:\n    response = requests.get(url, timeout=5)\n    response.raise_for_status()\n    return response.json()\n```\n\n### TypeScript\u002FJavaScript Error Handling\n\n**Custom Error Classes:**\n\n```typescript\n\u002F\u002F Custom error classes\nclass ApplicationError extends Error {\n  constructor(\n    message: string,\n    public code: string,\n    public statusCode: number = 500,\n    public details?: Record\u003Cstring, any>,\n  ) {\n    super(message);\n    this.name = this.constructor.name;\n    Error.captureStackTrace(this, this.constructor);\n  }\n}\n\nclass ValidationError extends ApplicationError {\n  constructor(message: string, details?: Record\u003Cstring, any>) {\n    super(message, \"VALIDATION_ERROR\", 400, details);\n  }\n}\n\nclass NotFoundError extends ApplicationError {\n  constructor(resource: string, id: string) {\n    super(`${resource} not found`, \"NOT_FOUND\", 404, { resource, id });\n  }\n}\n\n\u002F\u002F Usage\nfunction getUser(id: string): User {\n  const user = users.find((u) => u.id === id);\n  if (!user) {\n    throw new NotFoundError(\"User\", id);\n  }\n  return user;\n}\n```\n\n**Result Type Pattern:**\n\n```typescript\n\u002F\u002F Result type for explicit error handling\ntype Result\u003CT, E = Error> = { ok: true; value: T } | { ok: false; error: E };\n\n\u002F\u002F Helper functions\nfunction Ok\u003CT>(value: T): Result\u003CT, never> {\n  return { ok: true, value };\n}\n\nfunction Err\u003CE>(error: E): Result\u003Cnever, E> {\n  return { ok: false, error };\n}\n\n\u002F\u002F Usage\nfunction parseJSON\u003CT>(json: string): Result\u003CT, SyntaxError> {\n  try {\n    const value = JSON.parse(json) as T;\n    return Ok(value);\n  } catch (error) {\n    return Err(error as SyntaxError);\n  }\n}\n\n\u002F\u002F Consuming Result\nconst result = parseJSON\u003CUser>(userJson);\nif (result.ok) {\n  console.log(result.value.name);\n} else {\n  console.error(\"Parse failed:\", result.error.message);\n}\n\n\u002F\u002F Chaining Results\nfunction chain\u003CT, U, E>(\n  result: Result\u003CT, E>,\n  fn: (value: T) => Result\u003CU, E>,\n): Result\u003CU, E> {\n  return result.ok ? fn(result.value) : result;\n}\n```\n\n**Async Error Handling:**\n\n```typescript\n\u002F\u002F Async\u002Fawait with proper error handling\nasync function fetchUserOrders(userId: string): Promise\u003COrder[]> {\n  try {\n    const user = await getUser(userId);\n    const orders = await getOrders(user.id);\n    return orders;\n  } catch (error) {\n    if (error instanceof NotFoundError) {\n      return []; \u002F\u002F Return empty array for not found\n    }\n    if (error instanceof NetworkError) {\n      \u002F\u002F Retry logic\n      return retryFetchOrders(userId);\n    }\n    \u002F\u002F Re-throw unexpected errors\n    throw error;\n  }\n}\n\n\u002F\u002F Promise error handling\nfunction fetchData(url: string): Promise\u003CData> {\n  return fetch(url)\n    .then((response) => {\n      if (!response.ok) {\n        throw new NetworkError(`HTTP ${response.status}`);\n      }\n      return response.json();\n    })\n    .catch((error) => {\n      console.error(\"Fetch failed:\", error);\n      throw error;\n    });\n}\n```\n\n### Rust Error Handling\n\n**Result and Option Types:**\n\n```rust\nuse std::fs::File;\nuse std::io::{self, Read};\n\n\u002F\u002F Result type for operations that can fail\nfn read_file(path: &str) -> Result\u003CString, io::Error> {\n    let mut file = File::open(path)?;  \u002F\u002F ? operator propagates errors\n    let mut contents = String::new();\n    file.read_to_string(&mut contents)?;\n    Ok(contents)\n}\n\n\u002F\u002F Custom error types\n#[derive(Debug)]\nenum AppError {\n    Io(io::Error),\n    Parse(std::num::ParseIntError),\n    NotFound(String),\n    Validation(String),\n}\n\nimpl From\u003Cio::Error> for AppError {\n    fn from(error: io::Error) -> Self {\n        AppError::Io(error)\n    }\n}\n\n\u002F\u002F Using custom error type\nfn read_number_from_file(path: &str) -> Result\u003Ci32, AppError> {\n    let contents = read_file(path)?;  \u002F\u002F Auto-converts io::Error\n    let number = contents.trim().parse()\n        .map_err(AppError::Parse)?;   \u002F\u002F Explicitly convert ParseIntError\n    Ok(number)\n}\n\n\u002F\u002F Option for nullable values\nfn find_user(id: &str) -> Option\u003CUser> {\n    users.iter().find(|u| u.id == id).cloned()\n}\n\n\u002F\u002F Combining Option and Result\nfn get_user_age(id: &str) -> Result\u003Cu32, AppError> {\n    find_user(id)\n        .ok_or_else(|| AppError::NotFound(id.to_string()))\n        .map(|user| user.age)\n}\n```\n\n### Go Error Handling\n\n**Explicit Error Returns:**\n\n```go\n\u002F\u002F Basic error handling\nfunc getUser(id string) (*User, error) {\n    user, err := db.QueryUser(id)\n    if err != nil {\n        return nil, fmt.Errorf(\"failed to query user: %w\", err)\n    }\n    if user == nil {\n        return nil, errors.New(\"user not found\")\n    }\n    return user, nil\n}\n\n\u002F\u002F Custom error types\ntype ValidationError struct {\n    Field   string\n    Message string\n}\n\nfunc (e *ValidationError) Error() string {\n    return fmt.Sprintf(\"validation failed for %s: %s\", e.Field, e.Message)\n}\n\n\u002F\u002F Sentinel errors for comparison\nvar (\n    ErrNotFound     = errors.New(\"not found\")\n    ErrUnauthorized = errors.New(\"unauthorized\")\n    ErrInvalidInput = errors.New(\"invalid input\")\n)\n\n\u002F\u002F Error checking\nuser, err := getUser(\"123\")\nif err != nil {\n    if errors.Is(err, ErrNotFound) {\n        \u002F\u002F Handle not found\n    } else {\n        \u002F\u002F Handle other errors\n    }\n}\n\n\u002F\u002F Error wrapping and unwrapping\nfunc processUser(id string) error {\n    user, err := getUser(id)\n    if err != nil {\n        return fmt.Errorf(\"process user failed: %w\", err)\n    }\n    \u002F\u002F Process user\n    return nil\n}\n\n\u002F\u002F Unwrap errors\nerr := processUser(\"123\")\nif err != nil {\n    var valErr *ValidationError\n    if errors.As(err, &valErr) {\n        fmt.Printf(\"Validation error: %s\\n\", valErr.Field)\n    }\n}\n```\n\n## Universal Patterns\n\n### Pattern 1: Circuit Breaker\n\nPrevent cascading failures in distributed systems.\n\n```python\nfrom enum import Enum\nfrom datetime import datetime, timedelta\nfrom typing import Callable, TypeVar\n\nT = TypeVar('T')\n\nclass CircuitState(Enum):\n    CLOSED = \"closed\"       # Normal operation\n    OPEN = \"open\"          # Failing, reject requests\n    HALF_OPEN = \"half_open\"  # Testing if recovered\n\nclass CircuitBreaker:\n    def __init__(\n        self,\n        failure_threshold: int = 5,\n        timeout: timedelta = timedelta(seconds=60),\n        success_threshold: int = 2\n    ):\n        self.failure_threshold = failure_threshold\n        self.timeout = timeout\n        self.success_threshold = success_threshold\n        self.failure_count = 0\n        self.success_count = 0\n        self.state = CircuitState.CLOSED\n        self.last_failure_time = None\n\n    def call(self, func: Callable[[], T]) -> T:\n        if self.state == CircuitState.OPEN:\n            if datetime.now() - self.last_failure_time > self.timeout:\n                self.state = CircuitState.HALF_OPEN\n                self.success_count = 0\n            else:\n                raise Exception(\"Circuit breaker is OPEN\")\n\n        try:\n            result = func()\n            self.on_success()\n            return result\n        except Exception as e:\n            self.on_failure()\n            raise\n\n    def on_success(self):\n        self.failure_count = 0\n        if self.state == CircuitState.HALF_OPEN:\n            self.success_count += 1\n            if self.success_count >= self.success_threshold:\n                self.state = CircuitState.CLOSED\n                self.success_count = 0\n\n    def on_failure(self):\n        self.failure_count += 1\n        self.last_failure_time = datetime.now()\n        if self.failure_count >= self.failure_threshold:\n            self.state = CircuitState.OPEN\n\n# Usage\ncircuit_breaker = CircuitBreaker()\n\ndef fetch_data():\n    return circuit_breaker.call(lambda: external_api.get_data())\n```\n\n### Pattern 2: Error Aggregation\n\nCollect multiple errors instead of failing on first error.\n\n```typescript\nclass ErrorCollector {\n  private errors: Error[] = [];\n\n  add(error: Error): void {\n    this.errors.push(error);\n  }\n\n  hasErrors(): boolean {\n    return this.errors.length > 0;\n  }\n\n  getErrors(): Error[] {\n    return [...this.errors];\n  }\n\n  throw(): never {\n    if (this.errors.length === 1) {\n      throw this.errors[0];\n    }\n    throw new AggregateError(\n      this.errors,\n      `${this.errors.length} errors occurred`,\n    );\n  }\n}\n\n\u002F\u002F Usage: Validate multiple fields\nfunction validateUser(data: any): User {\n  const errors = new ErrorCollector();\n\n  if (!data.email) {\n    errors.add(new ValidationError(\"Email is required\"));\n  } else if (!isValidEmail(data.email)) {\n    errors.add(new ValidationError(\"Email is invalid\"));\n  }\n\n  if (!data.name || data.name.length \u003C 2) {\n    errors.add(new ValidationError(\"Name must be at least 2 characters\"));\n  }\n\n  if (!data.age || data.age \u003C 18) {\n    errors.add(new ValidationError(\"Age must be 18 or older\"));\n  }\n\n  if (errors.hasErrors()) {\n    errors.throw();\n  }\n\n  return data as User;\n}\n```\n\n### Pattern 3: Graceful Degradation\n\nProvide fallback functionality when errors occur.\n\n```python\nfrom typing import Optional, Callable, TypeVar\n\nT = TypeVar('T')\n\ndef with_fallback(\n    primary: Callable[[], T],\n    fallback: Callable[[], T],\n    log_error: bool = True\n) -> T:\n    \"\"\"Try primary function, fall back to fallback on error.\"\"\"\n    try:\n        return primary()\n    except Exception as e:\n        if log_error:\n            logger.error(f\"Primary function failed: {e}\")\n        return fallback()\n\n# Usage\ndef get_user_profile(user_id: str) -> UserProfile:\n    return with_fallback(\n        primary=lambda: fetch_from_cache(user_id),\n        fallback=lambda: fetch_from_database(user_id)\n    )\n\n# Multiple fallbacks\ndef get_exchange_rate(currency: str) -> float:\n    return (\n        try_function(lambda: api_provider_1.get_rate(currency))\n        or try_function(lambda: api_provider_2.get_rate(currency))\n        or try_function(lambda: cache.get_rate(currency))\n        or DEFAULT_RATE\n    )\n\ndef try_function(func: Callable[[], Optional[T]]) -> Optional[T]:\n    try:\n        return func()\n    except Exception:\n        return None\n```\n\n## Best Practices\n\n1. **Fail Fast**: Validate input early, fail quickly\n2. **Preserve Context**: Include stack traces, metadata, timestamps\n3. **Meaningful Messages**: Explain what happened and how to fix it\n4. **Log Appropriately**: Error = log, expected failure = don't spam logs\n5. **Handle at Right Level**: Catch where you can meaningfully handle\n6. **Clean Up Resources**: Use try-finally, context managers, defer\n7. **Don't Swallow Errors**: Log or re-throw, don't silently ignore\n8. **Type-Safe Errors**: Use typed errors when possible\n\n```python\n# Good error handling example\ndef process_order(order_id: str) -> Order:\n    \"\"\"Process order with comprehensive error handling.\"\"\"\n    try:\n        # Validate input\n        if not order_id:\n            raise ValidationError(\"Order ID is required\")\n\n        # Fetch order\n        order = db.get_order(order_id)\n        if not order:\n            raise NotFoundError(\"Order\", order_id)\n\n        # Process payment\n        try:\n            payment_result = payment_service.charge(order.total)\n        except PaymentServiceError as e:\n            # Log and wrap external service error\n            logger.error(f\"Payment failed for order {order_id}: {e}\")\n            raise ExternalServiceError(\n                f\"Payment processing failed\",\n                service=\"payment_service\",\n                details={\"order_id\": order_id, \"amount\": order.total}\n            ) from e\n\n        # Update order\n        order.status = \"completed\"\n        order.payment_id = payment_result.id\n        db.save(order)\n\n        return order\n\n    except ApplicationError:\n        # Re-raise known application errors\n        raise\n    except Exception as e:\n        # Log unexpected errors\n        logger.exception(f\"Unexpected error processing order {order_id}\")\n        raise ApplicationError(\n            \"Order processing failed\",\n            code=\"INTERNAL_ERROR\"\n        ) from e\n```\n\n## Common Pitfalls\n\n- **Catching Too Broadly**: `except Exception` hides bugs\n- **Empty Catch Blocks**: Silently swallowing errors\n- **Logging and Re-throwing**: Creates duplicate log entries\n- **Not Cleaning Up**: Forgetting to close files, connections\n- **Poor Error Messages**: \"Error occurred\" is not helpful\n- **Returning Error Codes**: Use exceptions or Result types\n- **Ignoring Async Errors**: Unhandled promise rejections\n",{"name":5,"description":7},"main","12441d84a8a292fcc94f47bc98877cbefd9b52e2","plugins\u002F10x-swe\u002Fskills\u002Ferror-handling-patterns",0,"https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe","https:\u002F\u002Fgithub.com\u002Fcercova-studios","2026-11-12 00:33:06",{"source":8,"skillName":5,"commands":52,"prompt":62,"zipAvailable":63},[53,56,59],{"tool":54,"command":55},"npx","npx skills add cercova-studios\u002F10x-swe --skill error-handling-patterns",{"tool":57,"command":58},"bunx","bunx skills add cercova-studios\u002F10x-swe --skill error-handling-patterns",{"tool":60,"command":61},"pnpm","pnpm dlx skills add cercova-studios\u002F10x-swe --skill error-handling-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Ferror-handling-patterns\u002FSKILL.md",true,[],[66,106,141,161,180,192],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":70,"licenseFileUrl":71,"sourceHtmlUrl":72,"categories":73,"keywords":79,"publishedAt":39},"01M6CD3T6EQ9N5KPNXCM6ABHVA","turnstile-spin","Set up Cloudflare Turnstile end-to-end in a project. Scan the codebase, create the widget via the Cloudflare API, embed it where user requests need bot verification (form submissions, SPA actions, API endpoints, download links, comment or vote submissions, etc.), wire canonical server-side siteverify in the customer's existing backend, validate, and persist the skill. Load this when a user asks to add Turnstile, set up CAPTCHA, protect a form or endpoint from bots, or fix a Turnstile integration. Uses Cloudflare's documented Turnstile contract.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Fturnstile-spin\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Fturnstile-spin\u002FSKILL.md",[74],{"categoryNo":75,"categoryName":76,"taxonomyType":77,"taxonomyTypeDesc":78},"01JBSEEDCAT000000000000010","后端与接口","SCENARIO","使用场景",[80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,25],"turnstile spin","SET","nextjs","actions","up","fix","cloudflare","bot","api","permissions","create","astro","server","verification","plugin","endpoints","customer","backend","sveltekit","integration","app","bots","spa","project","end","SWE",{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":70,"licenseFileUrl":110,"sourceHtmlUrl":111,"categories":112,"keywords":124,"publishedAt":39},"01M6CD0BJYRNV610HYYPX933RE","frontend-design","Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Ffrontend-design\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Ffrontend-design\u002FSKILL.md",[113,116,119],{"categoryNo":114,"categoryName":115,"taxonomyType":77,"taxonomyTypeDesc":78},"01JBSEEDCAT000000000000009","前端开发",{"categoryNo":117,"categoryName":118,"taxonomyType":77,"taxonomyTypeDesc":78},"01JBSEEDCAT000000000000015","视觉设计",{"categoryNo":120,"categoryName":121,"taxonomyType":122,"taxonomyTypeDesc":123},"01JBSEEDCAT000000000000032","设计师","PROFESSION","适用职业",[125,126,127,90,128,129,38,130,131,132,37,133,134,135,136,137,138,25,139,140,34],"frontend design","frontend","design","web","quality","creative","web components","Production","code","components","user","generic","aesthetics","pages","with","high",{"skillNo":142,"name":143,"nameZh":6,"description":144,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":145,"categories":146,"keywords":147,"publishedAt":39},"01M6CD4QX8C4DST98AY21HEYCM","source-insights","Prepare inspected source evidence, preserve exact citations, and publish reviewed insights into an explicit local library.","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002Fknowledge\u002Fskills\u002Fsource-insights\u002FSKILL.md",[],[148,149,150,151,152,153,154,155,156,157,158,159,160],"source insights","insights","source","publish","Citations","evidence","library","workflows","prepare","session","global","local","preserve",{"skillNo":162,"name":163,"nameZh":6,"description":164,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":165,"categories":166,"keywords":170,"publishedAt":39},"01M6CD4N1HVNC1EXPEBZT7YS31","skill-graph","Discover skills and workflows through independent lexical search, relationship paths and a terminal graph.","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002Fknowledge\u002Fskills\u002Fskill-graph\u002FSKILL.md",[167],{"categoryNo":168,"categoryName":169,"taxonomyType":77,"taxonomyTypeDesc":78},"01JBSEEDCAT000000000000023","Skill与智能体开发",[171,172,94,155,173,174,175,158,176,177,178,105,179],"graph","skill graph","terminal","10x","search","discover skills","discover","paths","relationship",{"skillNo":181,"name":182,"nameZh":6,"description":183,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":184,"categories":185,"keywords":186,"publishedAt":39},"01M6CD4HQKXNZ57YEGD8QVK6Z6","session-search","Recall public session turns with exact provenance, bounded excerpts and independent piped exports.","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002Fknowledge\u002Fskills\u002Fsession-search\u002FSKILL.md",[],[175,157,187,188,155,189,190,158,139,149,150,191],"session search","public","provenance","recall","bounded",{"skillNo":193,"name":194,"nameZh":6,"description":195,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":196,"categories":197,"keywords":204,"publishedAt":39},"01M6CD4ET7DVNBYPDAMAYMSK2T","newsletter","Produce a private local AI newsletter from bounded public research, with cited deep dives, HTML\u002FMarkdown output, Dagu scheduling and seven-day retention.","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002Fknowledge\u002Fskills\u002Fnewsletter\u002FSKILL.md",[198,201],{"categoryNo":199,"categoryName":200,"taxonomyType":77,"taxonomyTypeDesc":78},"01JBSEEDCAT000000000000005","邮件与沟通",{"categoryNo":202,"categoryName":203,"taxonomyType":77,"taxonomyTypeDesc":78},"01JBSEEDCAT000000000000021","资料检索与研究",[194,205,206,207,208,188,155,209,210,211,212,158,139,213,214,159,191,215],"local ai","dagu","produce","research","markdown","scheduling","html","daily","deep","retention","output"]