python-error-handling▌
wshobson/agents · updated Apr 8, 2026
MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.
Structured input validation, exception design, and graceful failure handling for Python applications.
- ›Covers fail-fast validation patterns, meaningful exception hierarchies, and partial failure handling for batch operations
- ›Includes Pydantic integration for complex input validation with automatic error messages and custom exception types with context
- ›Demonstrates exception chaining to preserve debug trails, batch processing with per-item error tracking, and progress reporting for lon
Python Error Handling
Build robust Python applications with proper input validation, meaningful exceptions, and graceful failure handling. Good error handling makes debugging easier and systems more reliable.
When to Use This Skill
- Validating user input and API parameters
- Designing exception hierarchies for applications
- Handling partial failures in batch operations
- Converting external data to domain types
- Building user-friendly error messages
- Implementing fail-fast validation patterns
Core Concepts
1. Fail Fast
Validate inputs early, before expensive operations. Report all validation errors at once when possible.
2. Meaningful Exceptions
Use appropriate exception types with context. Messages should explain what failed, why, and how to fix it.
3. Partial Failures
In batch operations, don't let one failure abort everything. Track successes and failures separately.
4. Preserve Context
Chain exceptions to maintain the full error trail for debugging.
Quick Start
def fetch_page(url: str, page_size: int) -> Page:
if not url:
raise ValueError("'url' is required")
if not 1 <= page_size <= 100:
raise ValueError(f"'page_size' must be 1-100, got {page_size}")
# Now safe to proceed...
Fundamental Patterns
Pattern 1: Early Input Validation
Validate all inputs at API boundaries before any processing begins.
def process_order(
order_id: str,
quantity: int,
discount_percent: float,
) -> OrderResult:
"""Process an order with validation."""
# Validate required fields
if not order_id:
raise ValueError("'order_id' is required")
# Validate ranges
if quantity <= 0:
raise ValueError(f"'quantity' must be positive, got {quantity}")
if not 0 <= discount_percent <= 100:
raise ValueError(
f"'discount_percent' must be 0-100, got {discount_percent}"
)
# Validation passed, proceed with processing
return _process_validated_order(order_id, quantity, discount_percent)
Pattern 2: Convert to Domain Types Early
Parse strings and external data into typed domain objects at system boundaries.
from enum import Enum
class OutputFormat(Enum):
JSON = "json"
CSV = "csv"
PARQUET = "parquet"
def parse_output_format(value: str) -> OutputFormat:
"""Parse string to OutputFormat enum.
Args:
value: Format string from user input.
Returns:
Validated OutputFormat enum member.
Raises:
ValueError: If format is not recognized.
"""
try:
return OutputFormat(value.lower())
except ValueError:
valid_formats = [f.value for f in OutputFormat]
raise ValueError(
f"Invalid format '{value}'. "
f"Valid options: {', '.join(valid_formats)}"
)
# Usage at API boundary
def export_data(data: list[dict], format_str: str) -> bytes:
output_format = parse_output_format(format_str) # Fail fast
# Rest of function uses typed OutputFormat
...
Pattern 3: Pydantic for Complex Validation
Use Pydantic models for structured input validation with automatic error messages.
from pydantic import BaseModel, Field, field_validator
class CreateUserInput(BaseModel):
"""Input model for user creation."""
email: str = Field(..., min_length=5, max_length=255)
name: str = Field(..., min_length=1, max_length=100)
age: int = Field(ge=0, le=150)
@field_validator("email")
@classmethod
def validate_email_format(cls, v: str) -> str:
if "@" not in v or "." not in v.split("@")[-1]:
raise ValueError("Invalid email format")
return v.lower()
@field_validator("name")
@classmethod
def normalize_name(cls, v: str) -> str:
return v.strip().title()
# Usage
try:
user_input = CreateUserInput(
email="[email protected]",
name="john doe",
age=25,
)
except ValidationError as e:
# Pydantic provides detailed error information
print(e.errors())
Pattern 4: Map Errors to Standard Exceptions
Use Python's built-in exception types appropriately, adding context as needed.
| Failure Type | Exception | Example |
|---|---|---|
| Invalid input | ValueError |
Bad parameter values |
| Wrong type | TypeError |
Expected string, got int |
| Missing item | KeyError |
Dict key not found |
| Operational failure | RuntimeError |
Service unavailable |
| Timeout | TimeoutError |
Operation took too long |
| File not found | FileNotFoundError |
Path doesn't exist |
| Permission denied | PermissionError |
Access forbidden |
# Good: Specific exception with context
raise ValueError(f"'page_size' must be 1-100, got {page_size}")
# Avoid: Generic exception, no context
raise Exception("Invalid parameter")
Advanced Patterns
Pattern 5: Custom Exceptions with Context
Create domain-specific exceptions that carry structured information.
class ApiError(Exception):
"""Base exception for API errors."""
def __init__(
self,
message: str,
status_code: int,
response_body: str | None = None,
) -> None:
self.status_code = status_code
self.response_body = response_body
super(How to use python-error-handling on Cursor
AI-first code editor with Composer
Prerequisites
Before installing skills in Cursor, ensure your development environment meets these requirements:
- ›Cursor installed and configured on your development machine
- ›Node.js version 16.0+ with npm package manager (verify with
node --version) - ›Active project directory or workspace where you want to add python-error-handling
Execute installation command
Execute the skills CLI command in your project's root directory to begin installation:
The skills CLI fetches python-error-handling from GitHub repository wshobson/agents and configures it for Cursor.
Select Cursor when prompted
The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:
Verify installation
Confirm successful installation by checking the skill directory location:
Reload or restart Cursor to activate python-error-handling. Access the skill through slash commands (e.g., /python-error-handling) or your agent's skill management interface.
Security & Verification Notice
We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.
Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.
List & Monetize Your Skill
Submit your Claude Code skill and start earning
Use Cases▌
Task Automation & Efficiency
Automate repetitive workflows and reduce manual effort
Example
Generate reports, summarize documents, draft communications
Save 3-5 hours per week on routine tasks
Knowledge Enhancement
Learn new skills, understand complex topics, get expert guidance
Example
Explain concepts, provide examples, suggest learning resources
Accelerate learning and skill development by 2x
Quality Improvement
Enhance output quality through reviews, suggestions, and refinements
Example
Review drafts, suggest improvements, catch errors
Improve work quality by 30-40% with less effort
Implementation Guide▌
Prerequisites
- ›Claude Desktop or compatible AI client with skill support
- ›Clear understanding of task or problem to solve
- ›Willingness to iterate and refine outputs
Time Estimate
15-45 minutes depending on use case complexity
Installation Steps
- 1.Install skill using provided installation command
- 2.Test with simple use case relevant to your work
- 3.Evaluate output quality and relevance
- 4.Iterate on prompts to improve results
- 5.Integrate into regular workflow if valuable
Common Pitfalls
- ⚠Expecting perfect results without iteration
- ⚠Not providing enough context in prompts
- ⚠Using skill for tasks outside its intended scope
- ⚠Accepting outputs without review and validation
Best Practices▌
✓ Do
- +Start with clear, specific prompts
- +Provide relevant context and constraints
- +Review and refine all outputs before using
- +Iterate to improve output quality
- +Document successful prompt patterns
✗ Don't
- −Don't use without understanding skill limitations
- −Don't skip validation of outputs
- −Don't share sensitive information in prompts
- −Don't expect skill to replace human judgment
💡 Pro Tips
- ★Be specific about desired format and style
- ★Ask for multiple options to choose from
- ★Request explanations to understand reasoning
- ★Combine AI efficiency with human expertise
When to Use This▌
✓ Use When
Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.
✗ Avoid When
Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.
Learning Path▌
- 1Familiarize yourself with skill capabilities and limitations
- 2Start with low-risk, non-critical tasks
- 3Progress to more complex and valuable use cases
- 4Build expertise through regular use and experimentation
Discussion
Product Hunt–style comments (not star reviews)- No comments yet — start the thread.
Ratings
4.6★★★★★59 reviews- ★★★★★Carlos Taylor· Dec 28, 2024
python-error-handling is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.
- ★★★★★Jin Chawla· Dec 24, 2024
Useful defaults in python-error-handling — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.
- ★★★★★Carlos Anderson· Dec 20, 2024
Keeps context tight: python-error-handling is the kind of skill you can hand to a new teammate without a long onboarding doc.
- ★★★★★Pratham Ware· Dec 12, 2024
python-error-handling is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.
- ★★★★★Ava Malhotra· Nov 19, 2024
Keeps context tight: python-error-handling is the kind of skill you can hand to a new teammate without a long onboarding doc.
- ★★★★★Soo Menon· Nov 15, 2024
python-error-handling has been reliable in day-to-day use. Documentation quality is above average for community skills.
- ★★★★★Carlos Reddy· Nov 11, 2024
python-error-handling is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.
- ★★★★★Yash Thakker· Nov 3, 2024
Keeps context tight: python-error-handling is the kind of skill you can hand to a new teammate without a long onboarding doc.
- ★★★★★Dhruvi Jain· Oct 22, 2024
python-error-handling has been reliable in day-to-day use. Documentation quality is above average for community skills.
- ★★★★★William Perez· Oct 10, 2024
python-error-handling has been reliable in day-to-day use. Documentation quality is above average for community skills.
showing 1-10 of 59