extractum-skills / rules
Cursor rule44 starsChanged 10 months agoMITView on GitHub
Error handling and validation patterns
- Reads credentials
Where files are headingNew Cursor rule files have more rules about planning and tracking tasks, and fewer about code style.
Of the Cursor rule files we read, the 1,531 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository7 other files it gives its agents.
- .cursor/rules/00-project-overview.mdcCursor rule
- .cursor/rules/05-solution-design.mdcCursor rule
- .cursor/rules/10-python-standards.mdcCursor rule
- .cursor/rules/20-type-annotations.mdcCursor rule
- .cursor/rules/30-logging-standards.mdcCursor rule
- .cursor/rules/40-docstrings.mdcCursor rule
- .cursor/rules/60-async-patterns.mdcCursor rule
The file
We split this 50-error-handling.mdc into the rules it gives an agent
3 rules. About 0 are common, 3 are distinctive, and 0 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 17
Always re-raise: after logging — never swallow exceptions
- Distinctive: line 101
Use try/except with proper logging:
- Distinctive: line 134
Use proper exit codes for script termination:
≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
---
description: "Error handling and validation patterns"
globs:
- "**/*.py"
alwaysApply: false
priority: 5
---
# Error Handling Standards
## Fail Fast Principle
**Never suppress errors.** Errors must be raised immediately to prevent silent failures.
### Rules
1. **Always re-raise** after logging — never swallow exceptions
2. **Validate early** — check inputs at function entry, not deep in logic
3. **No bare except** — always specify exception types or use `Exception`
4. **No pass in except** — always handle, log, or re-raise
```python
# ✅ Good - Fail fast, log and re-raise
try:
result = await some_operation()
except Exception as e:
logger.error(f"Operation failed: {e}", exc_info=True)
raise # Always re-raise!
# ❌ Bad - Suppressed error (NEVER DO THIS)
try:
result = await some_operation()
except Exception:
pass # Silent failure - bugs will be hidden!
# ❌ Bad - Logged but not raised
try:
result = await some_operation()
except Exception as e:
logger.error(f"Failed: {e}") # Error is lost, caller doesn't know!
return None
```
### Early Validation Pattern
```python
async def run_agent(prompt: str, logger: logging.Logger) -> AgentResultSummary:
"""Run agent - validates inputs immediately."""
# Fail fast: validate at entry point
load_dotenv()
_validate_api_key() # Raises immediately if missing
_validate_prompt(prompt) # Raises immediately if invalid
# Only proceed if all validations pass
options: ClaudeAgentOptions = _create_agent_options()
...
```
---
## Error Message Constants
Define error messages as multiline string constants:
```python
ERROR_API_KEY_MISSING: str = """
ANTHROPIC_API_KEY not found in environment variables.
Please ensure it is set in your .env file.
"""
ERROR_INVALID_PROMPT: str = """
Prompt cannot be empty.
Please provide a valid prompt for the agent.
"""
```
---
## Validation Functions
Extract validation logic into dedicated functions:
```python
def _validate_api_key() -> None:
"""Validate that the API key is available in environment."""
api_key: str | None = os.getenv(ENV_API_KEY)
if not api_key:
raise ValueError(ERROR_API_KEY_MISSING.strip())
def _validate_prompt(prompt: str) -> None:
"""Validate that the prompt is not empty."""
if not prompt or not prompt.strip():
raise ValueError(ERROR_INVALID_PROMPT.strip())
```
---
## Exception Handling Pattern
Use try/except with proper logging:
```python
try:
async for message in query(prompt=prompt, options=options):
# Process messages...
pass
except Exception as e:
logger.error(f"Agent execution failed: {e}", exc_info=True)
result_summary["error"] = str(e)
raise
```
---
## Graceful Degradation
Handle optional values with sensible defaults:
```python
# ✅ Good - Handle None with default
result_summary["total_cost_usd"] = message.total_cost_usd or 0.0
# ✅ Good - Use .get() for optional keys
if result.get("session_id"):
logger.info(f"Session ID: {result['session_id']}")
```
---
## Exit Codes
Use proper exit codes for script termination:
```python
import sys
# Success
sys.exit(0)
# General error
sys.exit(1)
# Specific error codes (optional)
EXIT_SUCCESS: int = 0
EXIT_ERROR: int = 1
EXIT_INVALID_ARGS: int = 2
```
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.

