[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6H9QC85HSMXE123EYEH3XFY":3,"skill-same:01M6H9QC85HSMXE123EYEH3XFY":54},{"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":25,"linkOnly":26,"markdownContent":27,"markdownBody":28,"frontMatter":29,"refName":32,"commitSha":33,"skillDirectory":34,"forksCount":14,"repositoryHtmlUrl":35,"repositoryHomepageUrl":6,"ownerHtmlUrl":36,"ownerBlogUrl":37,"ownerDescription":38,"updatedAt":39,"install":40,"resources":53},"01M6H9QC85HSMXE123EYEH3XFY","error-handling",null,"Error handling best practices and patterns","NeuralBlitz\u002FMito","NeuralBlitz","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F79354388?v=4","01M6H8T2TFH477HRS0KTSTKR2E","David Riggs","01M6H8T2YQQDXPYM092P670Z21",0,"MIT","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Ferror-handling\u002FSKILL.md",[],[19,20,21,22,23,24],"error handling","error","best practices","programming","opencode","patterns","2026-11-10 10:12:30",false,"---\nname: error-handling\ndescription: Error handling best practices and patterns\nlicense: MIT\ncompatibility: opencode\nmetadata:\n  audience: developers\n  category: programming\n---\n## What I do\n- Design error handling strategies\n- Create meaningful error messages\n- Handle exceptions properly\n- Implement error boundaries\n- Log errors effectively\n- Return appropriate HTTP status codes\n- Create custom exception hierarchies\n- Handle failures gracefully\n\n## When to use me\nWhen implementing error handling or designing exception strategies.\n\n## Exception Hierarchy\n```python\nfrom abc import ABC\nfrom typing import Optional, Dict, Any\nimport traceback\n\n\nclass AppException(ABC):\n    \"\"\"Base exception for application errors.\"\"\"\n    \n    def __init__(\n        self,\n        message: str,\n        code: str,\n        status_code: int = 500,\n        details: Optional[Dict[str, Any]] = None,\n        cause: Optional[Exception] = None,\n    ) -> None:\n        self.message = message\n        self.code = code\n        self.status_code = status_code\n        self.details = details or {}\n        self.cause = cause\n        super().__init__(message)\n    \n    def to_dict(self) -> Dict[str, Any]:\n        \"\"\"Convert exception to dictionary.\"\"\"\n        return {\n            \"error\": {\n                \"code\": self.code,\n                \"message\": self.message,\n                \"details\": self.details,\n            }\n        }\n\n\nclass ValidationError(AppException):\n    \"\"\"Raised when input validation fails.\"\"\"\n    \n    def __init__(\n        self,\n        message: str,\n        field: Optional[str] = None,\n        value: Any = None,\n        details: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        error_details = details or {}\n        if field:\n            error_details[\"field\"] = field\n        if value is not None:\n            error_details[\"value\"] = str(value)\n        \n        super().__init__(\n            message=message,\n            code=\"VALIDATION_ERROR\",\n            status_code=400,\n            details=error_details,\n        )\n\n\nclass NotFoundError(AppException):\n    \"\"\"Raised when a resource is not found.\"\"\"\n    \n    def __init__(\n        self,\n        resource_type: str,\n        resource_id: str,\n        details: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        super().__init__(\n            message=f\"{resource_type} with ID '{resource_id}' not found\",\n            code=\"NOT_FOUND\",\n            status_code=404,\n            details=details or {\"resource_type\": resource_type, \"id\": resource_id},\n        )\n\n\nclass ConflictError(AppException):\n    \"\"\"Raised when there's a resource conflict.\"\"\"\n    \n    def __init__(\n        self,\n        message: str,\n        details: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        super().__init__(\n            message=message,\n            code=\"CONFLICT\",\n            status_code=409,\n            details=details,\n        )\n\n\nclass AuthenticationError(AppException):\n    \"\"\"Raised when authentication fails.\"\"\"\n    \n    def __init__(\n        self,\n        message: str = \"Authentication required\",\n        details: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        super().__init__(\n            message=message,\n            code=\"UNAUTHORIZED\",\n            status_code=401,\n            details=details,\n        )\n\n\nclass AuthorizationError(AppException):\n    \"\"\"Raised when user is not authorized.\"\"\"\n    \n    def __init__(\n        self,\n        message: str = \"Access denied\",\n        details: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        super().__init__(\n            message=message,\n            code=\"FORBIDDEN\",\n            status_code=403,\n            details=details,\n        )\n\n\nclass RateLimitError(AppException):\n    \"\"\"Raised when rate limit is exceeded.\"\"\"\n    \n    def __init__(\n        self,\n        retry_after: int = 60,\n        details: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        super().__init__(\n            message=\"Rate limit exceeded. Please retry later.\",\n            code=\"RATE_LIMIT_EXCEEDED\",\n            status_code=429,\n            details=details or {\"retry_after\": retry_after},\n        )\n\n\nclass ExternalServiceError(AppException):\n    \"\"\"Raised when external service call fails.\"\"\"\n    \n    def __init__(\n        self,\n        service_name: str,\n        message: str,\n        status_code: int = 503,\n        details: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        super().__init__(\n            message=f\"External service error: {service_name}\",\n            code=\"EXTERNAL_SERVICE_ERROR\",\n            status_code=status_code,\n            details=details or {\"service\": service_name},\n        )\n```\n\n## Error Handling Middleware\n```python\nimport logging\nfrom fastapi import Request, HTTPException\nfrom fastapi.responses import JSONResponse\nfrom starlette.middleware.base import BaseHTTPMiddleware\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass ErrorHandlingMiddleware(BaseHTTPMiddleware):\n    \"\"\"Handle exceptions and convert to HTTP responses.\"\"\"\n    \n    async def dispatch(self, request: Request, call_next):\n        try:\n            response = await call_next(request)\n            return response\n        \n        except AppException as e:\n            logger.warning(\n                f\"App error: {e.code} - {e.message}\",\n                extra={\n                    \"code\": e.code,\n                    \"status_code\": e.status_code,\n                    \"details\": e.details,\n                    \"path\": request.url.path,\n                }\n            )\n            \n            return JSONResponse(\n                status_code=e.status_code,\n                content=e.to_dict(),\n                headers={\"X-Error-Code\": e.code},\n            )\n        \n        except HTTPException as e:\n            return JSONResponse(\n                status_code=e.status_code,\n                content={\"error\": {\"code\": \"HTTP_ERROR\", \"message\": e.detail}},\n            )\n        \n        except ValueError as e:\n            logger.warning(f\"Validation error: {e}\", extra={\"path\": request.url.path})\n            \n            return JSONResponse(\n                status_code=400,\n                content={\n                    \"error\": {\n                        \"code\": \"VALIDATION_ERROR\",\n                        \"message\": str(e),\n                    }\n                },\n            )\n        \n        except Exception as e:\n            logger.error(\n                f\"Unexpected error: {e}\",\n                extra={\n                    \"traceback\": traceback.format_exc(),\n                    \"path\": request.url.path,\n                }\n            )\n            \n            return JSONResponse(\n                status_code=500,\n                content={\n                    \"error\": {\n                        \"code\": \"INTERNAL_ERROR\",\n                        \"message\": \"An unexpected error occurred\",\n                    }\n                },\n            )\n```\n\n## Result Pattern\n```python\nfrom typing import Generic, TypeVar, Union, Optional\n\n\nT = TypeVar('T')\n\n\nclass Result(Generic[T]):\n    \"\"\"\n    Result type for operations that can fail.\n    Provides safe error handling without exceptions.\n    \"\"\"\n    \n    def __init__(\n        self,\n        value: Optional[T] = None,\n        error: Optional[Exception] = None,\n    ) -> None:\n        self._value = value\n        self._error = error\n    \n    @classmethod\n    def success(cls, value: T) -> 'Result[T]':\n        \"\"\"Create a successful result.\"\"\"\n        return cls(value=value)\n    \n    @classmethod\n    def failure(cls, error: Exception) -> 'Result[T]':\n        \"\"\"Create a failed result.\"\"\"\n        return cls(error=error)\n    \n    @property\n    def is_success(self) -> bool:\n        \"\"\"Check if result is successful.\"\"\"\n        return self._error is None\n    \n    @property\n    def is_failure(self) -> bool:\n        \"\"\"Check if result is a failure.\"\"\"\n        return self._error is not None\n    \n    def get_value(self, default: T = None) -> T:\n        \"\"\"Get value or default.\"\"\"\n        return self._value if self.is_success else default\n    \n    def get_error(self) -> Optional[Exception]:\n        \"\"\"Get error.\"\"\"\n        return self._error\n    \n    def map(self, func) -> 'Result':\n        \"\"\"Map success value.\"\"\"\n        if self.is_success:\n            try:\n                return Result.success(func(self._value))\n            except Exception as e:\n                return Result.failure(e)\n        return self\n    \n    def flat_map(self, func) -> 'Result':\n        \"\"\"Flat map success value.\"\"\"\n        if self.is_success:\n            return func(self._value)\n        return self\n    \n    def or_else(self, default: T) -> T:\n        \"\"\"Get value or default.\"\"\"\n        return self._value if self.is_success else default\n    \n    def __repr__(self) -> str:\n        if self.is_success:\n            return f\"Result({self._value})\"\n        return f\"Result(error={self._error})\"\n\n\n# Usage\ndef get_user(user_id: str) -> Result[User]:\n    try:\n        user = database.get_user(user_id)\n        if not user:\n            return Result.failure(NotFoundError(\"User\", user_id))\n        return Result.success(user)\n    except DatabaseError as e:\n        return Result.failure(e)\n\n\nresult = get_user(\"123\")\n\nif result.is_success:\n    user = result.get_value()\n    print(f\"Found user: {user.name}\")\nelse:\n    error = result.get_error()\n    print(f\"Error: {error}\")\n```\n\n## Retry Logic\n```python\nimport asyncio\nfrom functools import wraps\nfrom typing import Callable, TypeVar, List\nimport time\n\n\nT = TypeVar('T')\n\n\nclass RetryConfig:\n    \"\"\"Configuration for retry behavior.\"\"\"\n    \n    def __init__(\n        self,\n        max_retries: int = 3,\n        base_delay: float = 1.0,\n        max_delay: float = 60.0,\n        exponential_base: float = 2.0,\n        jitter: float = 0.1,\n        retryable_exceptions: tuple = (Exception,),\n    ) -> None:\n        self.max_retries = max_retries\n        self.base_delay = base_delay\n        self.max_delay = max_delay\n        self.exponential_base = exponential_base\n        self.jitter = jitter\n        self.retryable_exceptions = retryable_exceptions\n    \n    def calculate_delay(self, attempt: int) -> float:\n        \"\"\"Calculate delay for attempt number.\"\"\"\n        delay = self.base_delay * (self.exponential_base ** attempt)\n        delay = min(delay, self.max_delay)\n        \n        # Add jitter\n        jitter_amount = delay * self.jitter\n        delay += time.uniform(-jitter_amount, jitter_amount)\n        \n        return max(0, delay)\n\n\ndef retry(\n    config: RetryConfig = None,\n):\n    \"\"\"Decorator for retrying failed functions.\"\"\"\n    def decorator(func: Callable[..., T]) -> Callable[..., T]:\n        @wraps(func)\n        async def async_wrapper(*args, **kwargs) -> T:\n            config = config or RetryConfig()\n            last_exception = None\n            \n            for attempt in range(config.max_retries + 1):\n                try:\n                    return await func(*args, **kwargs)\n                except config.retryable_exceptions as e:\n                    last_exception = e\n                    \n                    if attempt >= config.max_retries:\n                        raise\n                    \n                    delay = config.calculate_delay(attempt)\n                    print(f\"Retry {attempt + 1}\u002F{config.max_retries} \"\n                          f\"after {delay:.2f}s: {e}\")\n                    \n                    await asyncio.sleep(delay)\n            \n            raise last_exception\n        \n        @wraps(func)\n        def sync_wrapper(*args, **kwargs) -> T:\n            config = config or RetryConfig()\n            last_exception = None\n            \n            for attempt in range(config.max_retries + 1):\n                try:\n                    return func(*args, **kwargs)\n                except config.retryable_exceptions as e:\n                    last_exception = e\n                    \n                    if attempt >= config.max_retries:\n                        raise\n                    \n                    delay = config.calculate_delay(attempt)\n                    print(f\"Retry {attempt + 1}\u002F{config.max_retries} \"\n                          f\"after {delay:.2f}s: {e}\")\n                    \n                    time.sleep(delay)\n            \n            raise last_exception\n        \n        return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper\n    \n    return decorator\n\n\n# Usage\n@retry(RetryConfig(max_retries=3, base_delay=0.5))\nasync def fetch_from_api(url: str) -> dict:\n    async with aiohttp.ClientSession() as session:\n        async with session.get(url) as response:\n            response.raise_for_status()\n            return await response.json()\n```\n\n## Error Codes Reference\n```\nHTTP Status Codes:\n400 - Bad Request (validation, malformed)\n401 - Unauthorized (authentication required)\n403 - Forbidden (not authorized)\n404 - Not Found (resource doesn't exist)\n409 - Conflict (state conflict)\n422 - Unprocessable Entity (validation errors)\n429 - Too Many Requests (rate limit)\n500 - Internal Server Error\n502 - Bad Gateway\n503 - Service Unavailable\n504 - Gateway Timeout\n\nApplication Error Codes:\nVALIDATION_ERROR - Input validation failed\nNOT_FOUND - Resource not found\nCONFLICT - State conflict\nUNAUTHORIZED - Authentication required\nFORBIDDEN - Not authorized\nRATE_LIMIT_EXCEEDED - Rate limit hit\nEXTERNAL_SERVICE_ERROR - External service failed\nTIMEOUT - Operation timed out\nPERMISSION_DENIED - Insufficient permissions\nDUPLICATE_ENTRY - Resource already exists\n```\n\n## Best Practices\n```\n1. Use specific exception types\n   Don't catch generic Exception\n\n2. Include context in errors\n   What happened? Where? What caused it?\n\n3. Log exceptions appropriately\n   DEBUG for expected, ERROR for unexpected\n\n4. Don't expose internals\n   Don't leak stack traces to users\n\n5. Handle failures gracefully\n   Provide helpful error messages\n\n6. Use result types for recoverable errors\n   Exceptions for exceptional situations\n\n7. Retry transient failures\n   Network issues, timeouts\n\n8. Document error codes\n   For API consumers\n\n9. Use proper HTTP status codes\n   Match semantics to status\n\n10. Clean up resources in finally\n    Use context managers\n```\n","## What I do\n- Design error handling strategies\n- Create meaningful error messages\n- Handle exceptions properly\n- Implement error boundaries\n- Log errors effectively\n- Return appropriate HTTP status codes\n- Create custom exception hierarchies\n- Handle failures gracefully\n\n## When to use me\nWhen implementing error handling or designing exception strategies.\n\n## Exception Hierarchy\n```python\nfrom abc import ABC\nfrom typing import Optional, Dict, Any\nimport traceback\n\n\nclass AppException(ABC):\n    \"\"\"Base exception for application errors.\"\"\"\n    \n    def __init__(\n        self,\n        message: str,\n        code: str,\n        status_code: int = 500,\n        details: Optional[Dict[str, Any]] = None,\n        cause: Optional[Exception] = None,\n    ) -> None:\n        self.message = message\n        self.code = code\n        self.status_code = status_code\n        self.details = details or {}\n        self.cause = cause\n        super().__init__(message)\n    \n    def to_dict(self) -> Dict[str, Any]:\n        \"\"\"Convert exception to dictionary.\"\"\"\n        return {\n            \"error\": {\n                \"code\": self.code,\n                \"message\": self.message,\n                \"details\": self.details,\n            }\n        }\n\n\nclass ValidationError(AppException):\n    \"\"\"Raised when input validation fails.\"\"\"\n    \n    def __init__(\n        self,\n        message: str,\n        field: Optional[str] = None,\n        value: Any = None,\n        details: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        error_details = details or {}\n        if field:\n            error_details[\"field\"] = field\n        if value is not None:\n            error_details[\"value\"] = str(value)\n        \n        super().__init__(\n            message=message,\n            code=\"VALIDATION_ERROR\",\n            status_code=400,\n            details=error_details,\n        )\n\n\nclass NotFoundError(AppException):\n    \"\"\"Raised when a resource is not found.\"\"\"\n    \n    def __init__(\n        self,\n        resource_type: str,\n        resource_id: str,\n        details: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        super().__init__(\n            message=f\"{resource_type} with ID '{resource_id}' not found\",\n            code=\"NOT_FOUND\",\n            status_code=404,\n            details=details or {\"resource_type\": resource_type, \"id\": resource_id},\n        )\n\n\nclass ConflictError(AppException):\n    \"\"\"Raised when there's a resource conflict.\"\"\"\n    \n    def __init__(\n        self,\n        message: str,\n        details: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        super().__init__(\n            message=message,\n            code=\"CONFLICT\",\n            status_code=409,\n            details=details,\n        )\n\n\nclass AuthenticationError(AppException):\n    \"\"\"Raised when authentication fails.\"\"\"\n    \n    def __init__(\n        self,\n        message: str = \"Authentication required\",\n        details: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        super().__init__(\n            message=message,\n            code=\"UNAUTHORIZED\",\n            status_code=401,\n            details=details,\n        )\n\n\nclass AuthorizationError(AppException):\n    \"\"\"Raised when user is not authorized.\"\"\"\n    \n    def __init__(\n        self,\n        message: str = \"Access denied\",\n        details: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        super().__init__(\n            message=message,\n            code=\"FORBIDDEN\",\n            status_code=403,\n            details=details,\n        )\n\n\nclass RateLimitError(AppException):\n    \"\"\"Raised when rate limit is exceeded.\"\"\"\n    \n    def __init__(\n        self,\n        retry_after: int = 60,\n        details: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        super().__init__(\n            message=\"Rate limit exceeded. Please retry later.\",\n            code=\"RATE_LIMIT_EXCEEDED\",\n            status_code=429,\n            details=details or {\"retry_after\": retry_after},\n        )\n\n\nclass ExternalServiceError(AppException):\n    \"\"\"Raised when external service call fails.\"\"\"\n    \n    def __init__(\n        self,\n        service_name: str,\n        message: str,\n        status_code: int = 503,\n        details: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        super().__init__(\n            message=f\"External service error: {service_name}\",\n            code=\"EXTERNAL_SERVICE_ERROR\",\n            status_code=status_code,\n            details=details or {\"service\": service_name},\n        )\n```\n\n## Error Handling Middleware\n```python\nimport logging\nfrom fastapi import Request, HTTPException\nfrom fastapi.responses import JSONResponse\nfrom starlette.middleware.base import BaseHTTPMiddleware\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass ErrorHandlingMiddleware(BaseHTTPMiddleware):\n    \"\"\"Handle exceptions and convert to HTTP responses.\"\"\"\n    \n    async def dispatch(self, request: Request, call_next):\n        try:\n            response = await call_next(request)\n            return response\n        \n        except AppException as e:\n            logger.warning(\n                f\"App error: {e.code} - {e.message}\",\n                extra={\n                    \"code\": e.code,\n                    \"status_code\": e.status_code,\n                    \"details\": e.details,\n                    \"path\": request.url.path,\n                }\n            )\n            \n            return JSONResponse(\n                status_code=e.status_code,\n                content=e.to_dict(),\n                headers={\"X-Error-Code\": e.code},\n            )\n        \n        except HTTPException as e:\n            return JSONResponse(\n                status_code=e.status_code,\n                content={\"error\": {\"code\": \"HTTP_ERROR\", \"message\": e.detail}},\n            )\n        \n        except ValueError as e:\n            logger.warning(f\"Validation error: {e}\", extra={\"path\": request.url.path})\n            \n            return JSONResponse(\n                status_code=400,\n                content={\n                    \"error\": {\n                        \"code\": \"VALIDATION_ERROR\",\n                        \"message\": str(e),\n                    }\n                },\n            )\n        \n        except Exception as e:\n            logger.error(\n                f\"Unexpected error: {e}\",\n                extra={\n                    \"traceback\": traceback.format_exc(),\n                    \"path\": request.url.path,\n                }\n            )\n            \n            return JSONResponse(\n                status_code=500,\n                content={\n                    \"error\": {\n                        \"code\": \"INTERNAL_ERROR\",\n                        \"message\": \"An unexpected error occurred\",\n                    }\n                },\n            )\n```\n\n## Result Pattern\n```python\nfrom typing import Generic, TypeVar, Union, Optional\n\n\nT = TypeVar('T')\n\n\nclass Result(Generic[T]):\n    \"\"\"\n    Result type for operations that can fail.\n    Provides safe error handling without exceptions.\n    \"\"\"\n    \n    def __init__(\n        self,\n        value: Optional[T] = None,\n        error: Optional[Exception] = None,\n    ) -> None:\n        self._value = value\n        self._error = error\n    \n    @classmethod\n    def success(cls, value: T) -> 'Result[T]':\n        \"\"\"Create a successful result.\"\"\"\n        return cls(value=value)\n    \n    @classmethod\n    def failure(cls, error: Exception) -> 'Result[T]':\n        \"\"\"Create a failed result.\"\"\"\n        return cls(error=error)\n    \n    @property\n    def is_success(self) -> bool:\n        \"\"\"Check if result is successful.\"\"\"\n        return self._error is None\n    \n    @property\n    def is_failure(self) -> bool:\n        \"\"\"Check if result is a failure.\"\"\"\n        return self._error is not None\n    \n    def get_value(self, default: T = None) -> T:\n        \"\"\"Get value or default.\"\"\"\n        return self._value if self.is_success else default\n    \n    def get_error(self) -> Optional[Exception]:\n        \"\"\"Get error.\"\"\"\n        return self._error\n    \n    def map(self, func) -> 'Result':\n        \"\"\"Map success value.\"\"\"\n        if self.is_success:\n            try:\n                return Result.success(func(self._value))\n            except Exception as e:\n                return Result.failure(e)\n        return self\n    \n    def flat_map(self, func) -> 'Result':\n        \"\"\"Flat map success value.\"\"\"\n        if self.is_success:\n            return func(self._value)\n        return self\n    \n    def or_else(self, default: T) -> T:\n        \"\"\"Get value or default.\"\"\"\n        return self._value if self.is_success else default\n    \n    def __repr__(self) -> str:\n        if self.is_success:\n            return f\"Result({self._value})\"\n        return f\"Result(error={self._error})\"\n\n\n# Usage\ndef get_user(user_id: str) -> Result[User]:\n    try:\n        user = database.get_user(user_id)\n        if not user:\n            return Result.failure(NotFoundError(\"User\", user_id))\n        return Result.success(user)\n    except DatabaseError as e:\n        return Result.failure(e)\n\n\nresult = get_user(\"123\")\n\nif result.is_success:\n    user = result.get_value()\n    print(f\"Found user: {user.name}\")\nelse:\n    error = result.get_error()\n    print(f\"Error: {error}\")\n```\n\n## Retry Logic\n```python\nimport asyncio\nfrom functools import wraps\nfrom typing import Callable, TypeVar, List\nimport time\n\n\nT = TypeVar('T')\n\n\nclass RetryConfig:\n    \"\"\"Configuration for retry behavior.\"\"\"\n    \n    def __init__(\n        self,\n        max_retries: int = 3,\n        base_delay: float = 1.0,\n        max_delay: float = 60.0,\n        exponential_base: float = 2.0,\n        jitter: float = 0.1,\n        retryable_exceptions: tuple = (Exception,),\n    ) -> None:\n        self.max_retries = max_retries\n        self.base_delay = base_delay\n        self.max_delay = max_delay\n        self.exponential_base = exponential_base\n        self.jitter = jitter\n        self.retryable_exceptions = retryable_exceptions\n    \n    def calculate_delay(self, attempt: int) -> float:\n        \"\"\"Calculate delay for attempt number.\"\"\"\n        delay = self.base_delay * (self.exponential_base ** attempt)\n        delay = min(delay, self.max_delay)\n        \n        # Add jitter\n        jitter_amount = delay * self.jitter\n        delay += time.uniform(-jitter_amount, jitter_amount)\n        \n        return max(0, delay)\n\n\ndef retry(\n    config: RetryConfig = None,\n):\n    \"\"\"Decorator for retrying failed functions.\"\"\"\n    def decorator(func: Callable[..., T]) -> Callable[..., T]:\n        @wraps(func)\n        async def async_wrapper(*args, **kwargs) -> T:\n            config = config or RetryConfig()\n            last_exception = None\n            \n            for attempt in range(config.max_retries + 1):\n                try:\n                    return await func(*args, **kwargs)\n                except config.retryable_exceptions as e:\n                    last_exception = e\n                    \n                    if attempt >= config.max_retries:\n                        raise\n                    \n                    delay = config.calculate_delay(attempt)\n                    print(f\"Retry {attempt + 1}\u002F{config.max_retries} \"\n                          f\"after {delay:.2f}s: {e}\")\n                    \n                    await asyncio.sleep(delay)\n            \n            raise last_exception\n        \n        @wraps(func)\n        def sync_wrapper(*args, **kwargs) -> T:\n            config = config or RetryConfig()\n            last_exception = None\n            \n            for attempt in range(config.max_retries + 1):\n                try:\n                    return func(*args, **kwargs)\n                except config.retryable_exceptions as e:\n                    last_exception = e\n                    \n                    if attempt >= config.max_retries:\n                        raise\n                    \n                    delay = config.calculate_delay(attempt)\n                    print(f\"Retry {attempt + 1}\u002F{config.max_retries} \"\n                          f\"after {delay:.2f}s: {e}\")\n                    \n                    time.sleep(delay)\n            \n            raise last_exception\n        \n        return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper\n    \n    return decorator\n\n\n# Usage\n@retry(RetryConfig(max_retries=3, base_delay=0.5))\nasync def fetch_from_api(url: str) -> dict:\n    async with aiohttp.ClientSession() as session:\n        async with session.get(url) as response:\n            response.raise_for_status()\n            return await response.json()\n```\n\n## Error Codes Reference\n```\nHTTP Status Codes:\n400 - Bad Request (validation, malformed)\n401 - Unauthorized (authentication required)\n403 - Forbidden (not authorized)\n404 - Not Found (resource doesn't exist)\n409 - Conflict (state conflict)\n422 - Unprocessable Entity (validation errors)\n429 - Too Many Requests (rate limit)\n500 - Internal Server Error\n502 - Bad Gateway\n503 - Service Unavailable\n504 - Gateway Timeout\n\nApplication Error Codes:\nVALIDATION_ERROR - Input validation failed\nNOT_FOUND - Resource not found\nCONFLICT - State conflict\nUNAUTHORIZED - Authentication required\nFORBIDDEN - Not authorized\nRATE_LIMIT_EXCEEDED - Rate limit hit\nEXTERNAL_SERVICE_ERROR - External service failed\nTIMEOUT - Operation timed out\nPERMISSION_DENIED - Insufficient permissions\nDUPLICATE_ENTRY - Resource already exists\n```\n\n## Best Practices\n```\n1. Use specific exception types\n   Don't catch generic Exception\n\n2. Include context in errors\n   What happened? Where? What caused it?\n\n3. Log exceptions appropriately\n   DEBUG for expected, ERROR for unexpected\n\n4. Don't expose internals\n   Don't leak stack traces to users\n\n5. Handle failures gracefully\n   Provide helpful error messages\n\n6. Use result types for recoverable errors\n   Exceptions for exceptional situations\n\n7. Retry transient failures\n   Network issues, timeouts\n\n8. Document error codes\n   For API consumers\n\n9. Use proper HTTP status codes\n   Match semantics to status\n\n10. Clean up resources in finally\n    Use context managers\n```\n",{"name":5,"license":15,"metadata":30,"description":7,"compatibility":23},{"audience":31,"category":22},"developers","main","2ea764e153842704d24a2e9aa4170441a7f03081",".opencode\u002Fskills\u002Ferror-handling","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito","https:\u002F\u002Fgithub.com\u002FNeuralBlitz","nuralnexus.org","Independent Multidisciplinary Researcher, Creative Producer, and AI Systems Architect\r\nAn independent creator and research-driven systems designer.","2026-11-12 03:13:05",{"source":8,"skillName":5,"commands":41,"prompt":51,"zipAvailable":52},[42,45,48],{"tool":43,"command":44},"npx","npx skills add NeuralBlitz\u002FMito --skill error-handling",{"tool":46,"command":47},"bunx","bunx skills add NeuralBlitz\u002FMito --skill error-handling",{"tool":49,"command":50},"pnpm","pnpm dlx skills add NeuralBlitz\u002FMito --skill error-handling","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Ferror-handling\u002FSKILL.md",true,[],[55,71,83,96,104,119],{"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":25},"01M6HAZSAQK1S27CEZYAYJTQDX","wireless-communications","Wireless systems, mobile networks, and 5G\u002F6G","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fwireless-communications\u002FSKILL.md",[],[62,63,64,65,66,67,68,69,23,70],"communications","wireless communications","wireless","systems","engineering","networks","5G","students","mobile",{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":25},"01M6HAZFX6E8NK3WZWDX5YCKYY","websockets","WebSocket implementation and best practices","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fwebassembly\u002Fwebsockets\u002FSKILL.md",[],[73,78,79,80,23,81,82,21],"websocket implementation","time","implementation","real-time","websocket",{"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":25},"01M6HAZ6DAXBQ7QHXXM1EM7715","vulnerability-auditing","Vulnerability assessment and auditing","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvulnerability-auditing\u002FSKILL.md",[],[90,91,92,93,23,94,95],"vulnerability","vulnerability auditing","security","vulnerability assessment","cybersecurity","assessment",{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":25},"01M6HAZ3FKF3CS9Z3J96RVE2ZE","vulnerability-assessment","Finding and assessing security vulnerabilities","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvue\u002Fvulnerability-assessment\u002FSKILL.md",[],[93,90,95,92,103,23],"vulnerabilities",{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":25},"01M6HAYSHM6HKRKEHFP0SGZQX7","vlsi-design","Very-Large-Scale Integration circuit design and semiconductor engineering","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvlsi-design\u002FSKILL.md",[],[111,112,113,114,115,66,116,23,117,69,118],"vlsi design","VLSI","design","hardware","integration","computer","scale","circuit",{"skillNo":120,"name":121,"nameZh":6,"description":122,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":123,"categories":124,"keywords":125,"publishedAt":25},"01M6HAYPQ30FFE2JXD7WQJ8R6C","unsupervised","Unsupervised learning concepts","https:\u002F\u002Fgithub.com\u002FNeuralBlitz\u002FMito\u002Fblob\u002Fmain\u002F.opencode\u002Fskills\u002Fvisualization\u002Funsupervised\u002FSKILL.md",[],[121,126,23,127,128,129,130,131],"learning","intelligence","unsupervised learning","machine","concepts","machine-learning"]