[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7FEJ9RXYFZP5ANVNTGPYDFX":3,"skill-same:01M7FEJ9RXYFZP5ANVNTGPYDFX":46},{"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":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M7FEJ9RXYFZP5ANVNTGPYDFX","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.","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Ferror-handling-patterns-agents-main\u002FSKILL.md",[],[],"2026-11-16 10:05:34",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","d69096e239f2a89aabc2cd078c47664a9d3b1e11","07-后端与架构\u002Ferror-handling-patterns-agents-main",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill error-handling-patterns",{"tool":38,"command":39},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill error-handling-patterns",{"tool":41,"command":42},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill error-handling-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Ferror-handling-patterns-agents-main\u002FSKILL.md",true,[],[47,54,59,66,73,80],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":19},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],{"skillNo":55,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"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":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]