Install the skill above, then run this in your AI tool:
/python-error-handling <your description>
About
Build robust Python applications with proper input validation, meaningful exceptions, and graceful failure handling. Good error handling makes debugging easier and systems more reliable.
Source
What gets added to your project
Preview every file this package writes on install before you run the command above.
Summary
Python error handling patterns including input validation, exception hierarchies, and partial failure handling. Use when implementing validation logic, designing exception strategies, handling batch processing failures, or building robus...
Skill instructions
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
python
deffetch_page(url: str, page_size: int) -> Page:
ifnot url:
raise ValueError("'url' is required")
ifnot1 <= 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.
python
defprocess_order(
order_id: str,
quantity: int,
discount_percent: float,
) -> OrderResult:
"""Process an order with validation."""# Validate required fieldsifnot order_id:
raise ValueError("'order_id' is required")
# Validate rangesif quantity <= 0:
raise ValueError(f"'quantity' must be positive, got {quantity}")
ifnot0 <= discount_percent <= 100:
raise ValueError(
f"'discount_percent' must be 0-100, got {discount_percent}"
)
# Validation passed, proceed with processingreturn _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.
python
from enum import Enum
classOutputFormat(Enum):
JSON = "json"
CSV = "csv"
PARQUET = "parquet"defparse_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 boundarydefexport_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.
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
python
# Good: Specific exception with contextraise ValueError(f"'page_size' must be 1-100, got {page_size}")
# Avoid: Generic exception, no contextraise Exception("Invalid parameter")
Detailed worked examples and patterns
Detailed sections (starting with ## Advanced Patterns) live in references/details.md. Read that file when the navigation summary above is insufficient.
Best Practices Summary
Validate early - Check inputs before expensive operations
Use specific exceptions - ValueError, TypeError, not generic Exception
Include context - Messages should explain what, why, and how to fix
Convert types at boundaries - Parse strings to enums/domain types early
Chain exceptions - Use raise ... from e to preserve debug info
Handle partial failures - Don't abort batches on single item errors
Use Pydantic - For complex input validation with structured errors
Document failure modes - Docstrings should list possible exceptions
Log with context - Include IDs, counts, and other debugging info
Test error paths - Verify exceptions are raised correctly
Add this badge to a GitHub README so readers can open the package page and install the same version.
[](https://www.aipm-registry.com/skills/wshobson/python-error-handling/1.0.0?utm_source=github&utm_medium=readme&utm_campaign=package_badge)
This imported publisher has not claimed its AIPM account. A connected account confirms account control, but it does not guarantee that a package is safe.
AI assistant context
What this skill is for
@wshobson/python-error-handling@1.0.0 is an AIPM skill package for All tools. Use it when a project needs the reusable AI behavior described as: Python error handling patterns including input validation, exception hierarchies, and partial failure handling. Use when implementing validation logic, designing exception strategies, handling batch processing failures, or building robus...
Run aipm add @wshobson/python-error-handling@1.0.0 in a project that has AIPM initialized.
Supported tools
@wshobson/python-error-handling@1.0.0 supports All tools.
Before installing
AIPM skills can add files to your project. Review the package name, target, description, license, and publisher before installing. Use a clean branch when trying a new skill.