[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7BWC91EZ79PB7F46EAST48D":3,"skill-same:01M7BWC91EZ79PB7F46EAST48D":47},{"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":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M7BWC91EZ79PB7F46EAST48D","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.","YYC-Cube\u002FYYC3-Knowledge-Base","YYC-Cube","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F235006543?v=4","01M79J2PH4SWD2X0825X6PN748","yyc3","01M79J2PHVK3F6ZBYT8K2SCZCW",1,"MIT","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fdeveloper-essentials\u002Fskills\u002Ferror-handling-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",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","87afe6ce96220accf50a345dea46784c8c9f210e","YYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fdeveloper-essentials\u002Fskills\u002Ferror-handling-patterns",0,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base","https:\u002F\u002Fkb.yyc3.top\u002F","https:\u002F\u002Fgithub.com\u002FYYC-Cube","万象归元于云枢 | 深栈智启新纪元","2026-11-10 10:37:32",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill error-handling-patterns",{"tool":39,"command":40},"bunx","bunx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill error-handling-patterns",{"tool":42,"command":43},"pnpm","pnpm dlx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill error-handling-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fdeveloper-essentials\u002Fskills\u002Ferror-handling-patterns\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M7CTDWHERCXPQCP0K03A86AS","vercel-sandbox","Run agent-browser + Chrome inside Vercel Sandbox microVMs for browser automation from any Vercel-deployed app. Use when the user needs browser automation in a Vercel app (Next.js, SvelteKit, Nuxt, Remix, Astro, etc.), wants to run headless Chrome without binary size limits, needs persistent browser sessions across commands, or wants ephemeral isolated browser environments. Triggers include \"Vercel Sandbox browser\", \"microVM Chrome\", \"agent-browser in sandbox\", \"browser automation on Vercel\", or any task requiring Chrome in a Vercel Sandbox.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fvercel-sandbox\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M7CTD8D2BNJY54S65M47HEJA","slack","Interact with Slack workspaces using browser automation. Use when the user needs to check unread channels, navigate Slack, send messages, extract data, find information, search conversations, or automate any Slack task. Triggers include \"check my Slack\", \"what channels have unreads\", \"send a message to\", \"search Slack for\", \"extract from Slack\", \"find who said\", or any task requiring programmatic Slack interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fslack\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M7CTCSSB8ZP3Q58C3YZDZK1W","electron","Automate Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify, etc.) using agent-browser via Chrome DevTools Protocol. Use when the user needs to interact with an Electron app, automate a desktop app, connect to a running app, control a native app, or test an Electron application. Triggers include \"automate Slack app\", \"control VS Code\", \"interact with Discord app\", \"test this Electron app\", \"connect to desktop app\", or any task requiring automation of a native Electron application.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Felectron\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M7CTCBJY76688V4DCZGWFHGQ","dogfood","Systematically explore and test a web application to find bugs, UX issues, and other problems. Use when asked to \"dogfood\", \"QA\", \"exploratory test\", \"find issues\", \"bug hunt\", \"test this app\u002Fsite\u002Fplatform\", or review the quality of a web application. Produces a structured report with full reproduction evidence -- step-by-step screenshots, repro videos, and detailed repro steps for every issue -- so findings can be handed directly to the responsible teams.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fdogfood\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M7CTC4H0FFGVEAQR9PA4GA1A","agent-browser","Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to \"open a website\", \"fill out a form\", \"click a button\", \"take a screenshot\", \"scrape data from a page\", \"test this web app\", \"login to a site\", \"automate browser actions\", or any task requiring programmatic web interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fagent-browser\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M7CTBKVFYBG78FDSABSDJTTQ","shadcn","Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn\u002Fui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for \"shadcn init\", \"create an app with --preset\", \"switch to --preset\", and for building a design system or applying a DESIGN.md or brand spec to shadcn\u002Fui.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-UI-界面组件\u002FYYC3-UI-界面组件-ui\u002Fskills\u002Fshadcn\u002FSKILL.md",[],[]]