[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M70NRJC091MBSBZDJJ3S6DB4":3,"skill-same:01M70NRJC091MBSBZDJJ3S6DB4":68},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":47,"repositoryHtmlUrl":48,"repositoryHomepageUrl":49,"ownerHtmlUrl":50,"ownerBlogUrl":51,"ownerDescription":52,"updatedAt":53,"install":54,"resources":67},"01M70NRJC091MBSBZDJJ3S6DB4","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.","shengdabai\u002FTony-Claude-Code-Skills","shengdabai","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F116417419?v=4","01M70F6D2WY5PQV5A92BKYJQEW","Tony Sheng","01M70F6D3GAAAYZ5H4CC1G8VXM",3,"MIT","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fwshobson-agents\u002Fplugins\u002Fdeveloper-essentials\u002Fskills\u002Ferror-handling-patterns\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"patterns","error handling","error handling patterns","error","application","degradation","build","propagation","use","applications","graceful degradation","Error Propagation","master","result","designing apis","across","when","implementing","types","reliability","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- **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- 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- Network timeouts\n- Missing files\n- Invalid user input\n- API rate limits\n\n**Unrecoverable Errors:**\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```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```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```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```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(\n            `${resource} not found`,\n            'NOT_FOUND',\n            404,\n            { resource, id }\n        );\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```typescript\n\u002F\u002F Result type for explicit error handling\ntype Result\u003CT, E = Error> =\n    | { ok: true; value: T }\n    | { 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```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```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```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\n## Resources\n\n- **references\u002Fexception-hierarchy-design.md**: Designing error class hierarchies\n- **references\u002Ferror-recovery-strategies.md**: Recovery patterns for different scenarios\n- **references\u002Fasync-error-handling.md**: Handling errors in concurrent code\n- **assets\u002Ferror-handling-checklist.md**: Review checklist for error handling\n- **assets\u002Ferror-message-guide.md**: Writing helpful error messages\n- **scripts\u002Ferror-analyzer.py**: Analyze error patterns in logs\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- **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- 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- Network timeouts\n- Missing files\n- Invalid user input\n- API rate limits\n\n**Unrecoverable Errors:**\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```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```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```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```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(\n            `${resource} not found`,\n            'NOT_FOUND',\n            404,\n            { resource, id }\n        );\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```typescript\n\u002F\u002F Result type for explicit error handling\ntype Result\u003CT, E = Error> =\n    | { ok: true; value: T }\n    | { 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```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```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```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\n## Resources\n\n- **references\u002Fexception-hierarchy-design.md**: Designing error class hierarchies\n- **references\u002Ferror-recovery-strategies.md**: Recovery patterns for different scenarios\n- **references\u002Fasync-error-handling.md**: Handling errors in concurrent code\n- **assets\u002Ferror-handling-checklist.md**: Review checklist for error handling\n- **assets\u002Ferror-message-guide.md**: Writing helpful error messages\n- **scripts\u002Ferror-analyzer.py**: Analyze error patterns in logs\n",{"name":5,"description":7},"main","7850740bd837adb32f0a109ab2af82482196c6f2","skills\u002Fwshobson-agents\u002Fplugins\u002Fdeveloper-essentials\u002Fskills\u002Ferror-handling-patterns",1,"https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills","https:\u002F\u002Fzturnsgo.com","https:\u002F\u002Fgithub.com\u002Fshengdabai","https:\u002F\u002Fzturnsgo.com\u002F","AI × education creator — producer, not consumer. Taught 6,000+ learners; shipping learning tools & daily essays with Claude Code, practicing @xiaolai's way 🥋","2026-11-01 21:28:23",{"source":8,"skillName":5,"commands":55,"prompt":65,"zipAvailable":66},[56,59,62],{"tool":57,"command":58},"npx","npx skills add shengdabai\u002FTony-Claude-Code-Skills --skill error-handling-patterns",{"tool":60,"command":61},"bunx","bunx skills add shengdabai\u002FTony-Claude-Code-Skills --skill error-handling-patterns",{"tool":63,"command":64},"pnpm","pnpm dlx skills add shengdabai\u002FTony-Claude-Code-Skills --skill error-handling-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fwshobson-agents\u002Fplugins\u002Fdeveloper-essentials\u002Fskills\u002Ferror-handling-patterns\u002FSKILL.md",true,[],[69,78,86,94,102,110],{"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":73,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":77},"01M73H7XKBHE1ETQDZT94MF9HH","seedance-prompt-en","Write effective prompts for Jimeng Seedance 2.0 multimodal AI video generation. Use when users want to create video prompts using text, images, videos, and audio inputs with the @ reference system. Covers camera movements, effects replication, video extension, editing, music beat-matching, e-commerce ads, short dramas, and educational content.","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-prompt-en\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-prompt-en\u002FSKILL.md",[],[],"2026-11-11 15:11:14",{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":82,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":77},"01M73GRE9998Q1DZWC71N41JWG","onepage-pdf","Convert an HTML page into a single continuous-page PDF (one tall page, no pagination breaks), preserving desktop layout, backgrounds and selectable text. Use when the user asks to turn an HTML file\u002Freport\u002Fproposal into a \"single-page PDF\", \"long PDF\", \"不分页 PDF\", \"单页 PDF\", \"长图式 PDF\", or complains that an HTML-to-PDF export breaks into pages or cuts content. Supports optional string redaction with leak verification.","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fonepage-pdf\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fonepage-pdf\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":90,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":77},"01M73GQG1KZDADVPV3MHAT1J5A","native-feel-cross-platform-desktop","Use when the user is designing, prototyping, or rewriting a desktop app that must run on multiple OSes (macOS + Windows, optionally Linux) AND feel indistinguishable from a native app to its users — fast launch, native windowing, native input handling, native materials. Trigger words include \"cross-platform desktop\", \"Electron alternative\", \"Tauri vs native\", \"WebView wrapper\", \"near-native performance\", \"Raycast architecture\", \"WebKit\u002FWebView2 quirks\", \"WKWebView\", \"system tray app\", \"global hotkey app\", \"launcher app\". Do NOT trigger this skill for pure web apps, pure mobile apps, or for greenfield projects that have no native-feel requirement.","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fnative-feel-cross-platform-desktop\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fnative-feel-cross-platform-desktop\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":98,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":77},"01M73G87PDNSMKG2FHWCYER6N8","gstack","Router for the gstack skill suite. (gstack)","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fgstack\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fgstack\u002FSKILL.md",[],[],{"skillNo":103,"name":104,"nameZh":6,"description":105,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":106,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":77},"01M73G3EAQWKCM8DB8D0N0QSVG","fireworks-tech-graph","Use when the user wants to create any technical diagram - architecture, data flow, flowchart, sequence, agent\u002Fmemory, or concept map - and export as SVG+PNG. Trigger on: \"画图\" \"帮我画\" \"生成图\" \"做个图\" \"架构图\" \"流程图\" \"可视化一下\" \"出图\" \"generate diagram\" \"draw diagram\" \"visualize\" or any system\u002Fflow description the user wants illustrated.","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ffireworks-tech-graph\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ffireworks-tech-graph\u002FSKILL.md",[],[],{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":77},"01M73G086AXAH9DW1H5G5N3CPB","dbs-video-extract","接收抖音、小红书、微信视频号等短视频链接或分享文案，查询作品／账号数据并提取语音文字稿，按作者和标题归档为 Markdown。用户希望完整解析短视频、取得数据或文字稿时使用；运行前检查 TikHub 与轻抖使用凭证，缺少时用新手能理解的方式引导购买和安全配置。","https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fdbs-video-extract\u002FSKILL.md",[],[]]