[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6J5DHPJHEY8DDP68AM5F1VK":3,"skill-same:01M6J5DHPJHEY8DDP68AM5F1VK":59},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":34,"linkOnly":35,"markdownContent":36,"markdownBody":37,"frontMatter":38,"refName":39,"commitSha":40,"skillDirectory":41,"forksCount":13,"repositoryHtmlUrl":42,"repositoryHomepageUrl":6,"ownerHtmlUrl":43,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":44,"install":45,"resources":58},"01M6J5DHPJHEY8DDP68AM5F1VK","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.","jest-won\u002Farchi-ro","jest-won","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F170307740?v=4","01M6J5DDZB6Q1Y5F3NWNQSAE03","01M6J5DE3QGT24C87G4JA4XTEH",0,"MIT","https:\u002F\u002Fgithub.com\u002Fjest-won\u002Farchi-ro\u002Fblob\u002Fmain\u002Fskills\u002Fbackend\u002Ferror-handling-patterns\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33],"error handling","error handling patterns","patterns","error","applications","use","reliability","master","build","application","across","propagation","degradation","designing apis","types","implementing","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","# 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",{"name":5,"description":7},"main","c997e19776ffa338d4936e0fd166e9f91d2e3fbf","skills\u002Fbackend\u002Ferror-handling-patterns","https:\u002F\u002Fgithub.com\u002Fjest-won\u002Farchi-ro","https:\u002F\u002Fgithub.com\u002Fjest-won","2026-03-26 09:53:02",{"source":8,"skillName":5,"commands":46,"prompt":56,"zipAvailable":57},[47,50,53],{"tool":48,"command":49},"npx","npx skills add jest-won\u002Farchi-ro --skill error-handling-patterns",{"tool":51,"command":52},"bunx","bunx skills add jest-won\u002Farchi-ro --skill error-handling-patterns",{"tool":54,"command":55},"pnpm","pnpm dlx skills add jest-won\u002Farchi-ro --skill error-handling-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjest-won\u002Farchi-ro\u002Fblob\u002Fmain\u002Fskills\u002Fbackend\u002Ferror-handling-patterns\u002FSKILL.md",true,[],[60,82,106,125,132,146],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":34},"01M6J5G7JAFYK6EF7KCYNTRSFC","playwright","Browser automation for E2E testing, web scraping, and UI testing. Use when writing E2E tests, automating browser interactions, or validating UI.","https:\u002F\u002Fgithub.com\u002Fjest-won\u002Farchi-ro\u002Fblob\u002Fmain\u002Fskills\u002Ffrontend\u002Fplaywright\u002FSKILL.md",[],[62,67,68,69,70,23,71,72,73,74,75,76,77,78,79,80,81],"web","for","tests","ui testing","scraping","web scraping","e2e","ui","browser","e2e tests","e2e testing","automation","browser automation","writing","testing",{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":34},"01M6J5G3T5S6QM0S0XP74SWZPT","workflow-orchestrator","Use this agent when you need to design, implement, or optimize complex business process workflows with multiple states, error handling, and transaction management.","https:\u002F\u002Fgithub.com\u002Fjest-won\u002Farchi-ro\u002Fblob\u002Fmain\u002Fskills\u002Fcore\u002Fworkflow-orchestrator\u002FSKILL.md",[],[89,90,91,92,23,93,94,95,96,21,97,18,98,99,100,101,102,103,104,105],"workflow orchestrator","workflow","orchestrator","read","process","business","edit","write","grep","workflows","implement","design","optimize","you","with","states","transaction",{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":34},"01M6J5G0DBNSXSMFVTVFG3BVA2","ultrawork","Use for maximum-precision execution with strict explore-plan-execute-verify loops. Trigger when the user starts their message with 'ultrawork' or 'ult', or explicitly asks for autonomous execute-verify-fix behavior.","https:\u002F\u002Fgithub.com\u002Fjest-won\u002Farchi-ro\u002Fblob\u002Fmain\u002Fskills\u002Fcore\u002Fultrawork\u002FSKILL.md",[],[108,68,103,113,114,115,116,23,117,118,119,120,121,122,123,124],"fix","verify","trigger","message","execute","autonomous","user","behavior","plan","explore","loops","execution",{"skillNo":126,"name":127,"nameZh":6,"description":128,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":129,"categories":130,"keywords":131,"publishedAt":34},"01M6J5FZ7W1B300ZQT6D0YW830","test","테스트 라고 하면 작동.","https:\u002F\u002Fgithub.com\u002Fjest-won\u002Farchi-ro\u002Fblob\u002Fmain\u002Fskills\u002Fcore\u002Ftest\u002FSKILL.md",[],[127],{"skillNo":133,"name":134,"nameZh":6,"description":135,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":136,"categories":137,"keywords":138,"publishedAt":34},"01M6J5FTTBHVGPY85YMNNVN3MT","task-distributor","Use when distributing tasks across multiple agents or workers, managing queues, and balancing workloads to maximize throughput while respecting priorities and deadlines.","https:\u002F\u002Fgithub.com\u002Fjest-won\u002Farchi-ro\u002Fblob\u002Fmain\u002Fskills\u002Fcore\u002Ftask-distributor\u002FSKILL.md",[],[139,140,141,142,97,143,28,144,145,23,95,96,92],"task","task distributor","haiku","tasks","throughput","priorities","workers",{"skillNo":147,"name":148,"nameZh":6,"description":149,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":150,"categories":151,"keywords":152,"publishedAt":34},"01M6J5FQ3FKJCXZJFK037BESWY","performance-monitor","Use when establishing observability infrastructure to track system metrics, detect performance anomalies, and optimize resource usage across multi-agent environments.","https:\u002F\u002Fgithub.com\u002Fjest-won\u002Farchi-ro\u002Fblob\u002Fmain\u002Fskills\u002Fcore\u002Fperformance-monitor\u002FSKILL.md",[],[153,154,155,95,156,157,158,159,28,101,23,96,92,97,141,160,161,162,163,164],"monitor","performance","performance monitor","usage","environments","multi","detect","multi-agent","system","observability","metrics","infrastructure"]