python-error-handling
Skill2 starsChanged 10 months agoMITView on GitHub
Python error handling and debugging. Use this skill when implementing error handling, designing exception hierarchies, debugging issues, or adding logging. Covers exception patterns, custom exceptions, logging with structlog, debugging tools, and error recovery.
Files
Python Error Handling
Modern error handling, logging, and debugging patterns.
Core Principles
- Specific exceptions - Catch specific types, not
Exception - Fail fast - Raise errors early at source
- Context in errors - Include relevant information
- Log, don't just print - Structured, searchable logs
Exception Handling Patterns
Be specific about what you catch
# BAD - Too broad
try:
result = process_data()
except:
print("Error occurred")
# GOOD - Specific handling
try:
result = process_data()
except FileNotFoundError as e:
logger.error(f"Config file not found: {e}")
use_defaults()
except ValueError as e:
logger.error(f"Invalid data: {e}")
raise
except Exception as e:
logger.error(f"Unexpected error: {e}", exc_info=True)
raiseSee exception-patterns.md.
Custom Exceptions
Create domain-specific exceptions
class DataValidationError(ValueError):
"""Raised when data validation fails."""
pass
class APIError(Exception):
"""Base exception for API errors."""
def __init__(self, message: str, status_code: int):
self.message = message
self.status_code = status_code
super().__init__(self.message)
class APITimeout(APIError):
"""API request timeout."""
def __init__(self, message: str):
super().__init__(message, status_code=504)See custom-exceptions.md.
Context Managers for Cleanup
from contextlib import contextmanager
@contextmanager
def managed_resource(name):
resource = acquire_resource(name)
try:
yield resource
finally:
release_resource(resource) # Always called
with managed_resource("database") as db:
db.query("SELECT * FROM users")
# Even if exception, resource releasedLogging with Structlog
import structlog
logger = structlog.get_logger()
def process_order(order_id: str):
log = logger.bind(order_id=order_id)
try:
log.info("processing_order_started")
result = process(order_id)
log.info("processing_order_completed", result=result)
return result
except Exception as e:
log.error("processing_order_failed", error=str(e))
raiseSee logging-patterns.md.
Debugging Tools
Use pdb for interactive debugging
def complex_function(data):
# Set breakpoint
import pdb; pdb.set_trace()
# Or in Python 3.7+
breakpoint()
result = process(data)
return resultSee debugging-tools.md.
Error Recovery Patterns
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=4, max=10)
)
def unreliable_api_call():
"""Retry with exponential backoff."""
response = requests.get("https://api.example.com")
response.raise_for_status()
return response.json()See retry-patterns.md.
source: Python error handling best practices
Other versions7 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 7
- zebbern/termstack★ 4same name
- CodeWithBehnam/cc-docs★ 2same name
- liushikuan63/Qoder-Optimization★ 2same name
- NorkzYT/claude-code-autopilot★ 2same name
- drzioner/gitwise★ 1same name
- owenlamont/skills★ 1same name
- gabepublic/api-autonom-test-01★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
Used alongsideProjects with it also use python-configuration, python-observability and 7 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
Aver005Skillpython-configuration
Python configuration management via environment variables and typed settings. Use when externalizing config, setting up pydantic-settings, managing secrets, or implementing environment-specific behavior.
Also in 3 projects that use this
CodeWithBehnamSkillpython-observability
Python observability patterns including structured logging, metrics, and distributed tracing. Use when adding logging, implementing metrics collection, setting up tracing, or debugging production systems.
Also in 3 projects that use this
Aver005Skillpython-resource-management
Python resource management with context managers, cleanup patterns, and streaming. Use when managing connections, file handles, implementing cleanup logic, or building streaming responses with accumulated state.
Also in 3 projects that use this
CodeWithBehnamSkillpython-anti-patterns
Common Python anti-patterns to avoid. Use as a checklist when reviewing code, before finalizing implementations, or when debugging issues that might stem from known bad practices.
Also in 3 projects that use this
nilecuiSkillasync-python-patterns
Master Python asyncio, concurrent programming, and async/await patterns for high-performance applications. Use when building async APIs, concurrent systems, or I/O-bound applications requiring non-blocking operations.
Also in 3 projects that use this
xfstudioSkillpython-testing-patterns
Implement comprehensive testing strategies with pytest, fixtures, mocking, and test-driven development. Use when writing Python tests, setting up test suites, or implementing testing best practices.
Also in 3 projects that use this
- +2 more from Aver005
- +1 more from CodeWithBehnam
In this repository38 other files it gives its agents.
- Data Engineering Cloud InfrastructureSkill
- data-eng-data-qualitySkill
- data-eng-streaming-patternsSkill
- data-eng-testing-patternsSkill
- data-eng-warehouse-patternsSkill
- DevOps CI/CD PatternsSkill
- devops-docker-patternsSkill
- devops-monitoring-observabilitySkill
- devops-terraform-patternsSkill
- git-advanced-operationsSkill
- git-workflow-patternsSkill
- modern-python-patternsSkill
- python-api-developmentSkill
- python-async-patternsSkill
- python-data-pipelinesSkill
- python-data-wranglingSkill
- python-devops-automationSkill
- python-package-developmentSkill
- python-performanceSkill
- python-testingSkill
- customizing-vectors-rSkill
- designing-oop-rSkill
- developing-packages-rSkill
- metaprogramming-rlangSkill
- optimizing-rSkill
- writing-tidyverse-rSkill
- sql-advanced-featuresSkill
- sql-analytics-patternsSkill
- sql-data-modelingSkill
- SQL Integration PatternsSkill
- sql-query-fundamentalsSkill
- sql-query-optimizationSkill
- sql-transformationsSkill
- API DesignSkill
- webdev-html-css-patternsSkill
- webdev-javascript-fundamentalsSkill
- webdev-react-patternsSkill
- webdev-typescript-patternsSkill
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

