Lesson 6: Error Recovery & Edge Case Handling
Learn techniques for handling errors, edge cases, and unexpected outputs in your prompts.
Why Error Recovery Matters
Even the best prompts sometimes produce unexpected results. Mastering error recovery means you can handle edge cases gracefully and get reliable outputs even when things go wrong.
Common Error Types
| Error Type | Description | Example |
|---|---|---|
| Format Errors | Output doesn't match expected structure | JSON parse failures |
| Hallucination | Model invents facts or references | Fake citations, made-up statistics |
| Incomplete Output | Response cuts off mid-sentence | Long responses truncated |
| Off-Topic Drift | Model veers away from the task | Adding unrelated information |
| Refusal | Model declines to answer | "I can't help with that" |
| Bias | Output shows unfair preferences | Stereotypical associations |
Mental model: Think of error recovery as having a safety net — you plan for failure so you're never caught off guard.
Technique 1: Defensive Prompting
Anticipate errors and build safeguards into your prompts.
Example:
Write a product description for our new smartwatch.
Requirements:
- Exactly 3 paragraphs
- Include: features, benefits, call-to-action
- Do NOT include: competitor comparisons, pricing, fake statistics
- If you're unsure about a feature, say "up to" or omit it rather than guessing
Format: Markdown with H2 headers for each section.
Defensive techniques:
- Explicitly state what NOT to include
- Provide fallback instructions for uncertain cases
- Specify exact format requirements
- Include validation criteria
Technique 2: Output Validation Prompts
Ask the model to validate its own output before delivering it.
[Original task]
Before providing your final answer:
1. Check that all dates are plausible (not in the future for historical content)
2. Verify that all statistics have reasonable magnitudes
3. Ensure no competitor names are mentioned (unless specifically asked)
4. Confirm the response is within the specified length
5. If any check fails, correct the issue and explain what was wrong
Technique 3: Graceful Degradation
When the model can't complete the full task, get partial results with clear explanations.
Example:
Analyze this dataset and provide insights.
If you cannot complete the full analysis:
1. Explain what information is missing or unclear
2. Provide whatever insights you CAN derive
3. List exactly what additional information would be needed
4. Give a confidence level for the partial analysis
Never guess or make up data to fill gaps.
Technique 4: Retry Logic with Context
When the first attempt fails, provide context about what went wrong.
First attempt:
Convert this data to JSON format:
[Data here]
If output is malformed, retry with:
The previous JSON output had syntax errors. Here's what was wrong:
[Error details]
Please regenerate the JSON, ensuring:
- All strings are properly quoted
- No trailing commas
- Valid JSON syntax throughout
Here's the data again:
[Data here]
Technique 5: Boundary Testing
Explicitly test edge cases in your prompts.
Write a function that calculates the average of a list of numbers.
Handle these edge cases:
- Empty list: Return 0 or raise appropriate error
- Single element: Return that element
- Negative numbers: Include in average
- Zero values: Include in average
- Very large numbers: Handle without overflow
Show the function and test cases for each edge case.
Handling Specific Error Types
Fixing Hallucination
[Original prompt]
IMPORTANT: Only include information you are confident about.
- If you're unsure about a specific fact, say "I'm not certain, but..."
- Do not make up statistics, dates, or names
- If you cannot answer confidently, say so rather than guessing
Fixing Format Errors
Return your response as valid JSON with this exact structure:
{
"key1": "string value",
"key2": number,
"key3": ["array", "of", "strings"]
}
Before outputting, verify:
- All braces and brackets are balanced
- All strings use double quotes
- No trailing commas
- Numbers don't have quotes around them
Fixing Incomplete Output
Write a comprehensive guide about [topic].
IMPORTANT: This must be complete. Do not stop mid-sentence or say "to be continued."
If the content is long, structure it with clear sections so I know it's complete.
End with a clear conclusion or summary.
Building Error Recovery Into Workflows
Workflow Template:
Step 1: Generate initial response
Step 2: Validate against criteria:
- [ ] Format is correct
- [ ] All facts are verifiable
- [ ] Response is complete
- [ ] No off-topic content
Step 3: If validation fails:
- Identify specific issues
- Retry with corrective instructions
- Maximum 2 retries before asking for clarification
Step 4: Final delivery with confidence score
Common Mistakes to Avoid
- Mistake: Not specifying what "success" looks like — Fix: Always define validation criteria upfront.
- Mistake: Giving up after one failed attempt — Fix: Use retry logic with specific corrective feedback.
- Mistake: Ignoring edge cases — Fix: Explicitly test boundary conditions.
- Mistake: Assuming the model knows your constraints — Fix: State all requirements explicitly.
Professional Tips & Tricks
- Build a library of error recovery prompts for common issues.
- For critical workflows, always include a validation step.
- Track which errors occur most frequently — they become prevention items.
- Use "defensive prompting" by default for important content.
Key Takeaways
- Defensive prompting anticipates errors and builds safeguards.
- Output validation catches issues before delivery.
- Graceful degradation gets partial results when full completion isn't possible.
- Retry logic with context helps fix errors efficiently.
- Boundary testing ensures your prompts handle edge cases.
Next up: Building complete AI workflows with prompt chaining and orchestration.
# Error Recovery Templates
## Defensive Prompt Template
"[Task description]
Requirements:
- [Specific requirements]
IMPORTANT constraints:
- Do NOT include: [things to avoid]
- If unsure, [fallback instruction]
- Maximum length: [limit]
Format: [exact format specification]
Validate before delivering:
1. [Validation criterion 1]
2. [Validation criterion 2]
3. [Validation criterion 3]"
## Graceful Degradation Template
"[Task description]
If you cannot complete the full task:
1. Explain what information is missing
2. Provide whatever you CAN derive
3. List what additional info is needed
4. Give confidence level for partial results
Never guess or make up data."
## Retry Template
"The previous attempt had issues:
[Error details]
Please regenerate, ensuring:
- [Specific fix 1]
- [Specific fix 2]
Here's the original input:
[Input data]"
## Boundary Testing Template
"[Task description]
Handle these edge cases:
- Empty input: [Expected behavior]
- Single item: [Expected behavior]
- Invalid input: [Expected behavior]
- Large input: [Expected behavior]
Show solutions for each case."Lesson Code (Python)
# Error Recovery Templates
## Defensive Prompt Template
"[Task description]
Requirements:
- [Specific requirements]
IMPORTANT constraints:
- Do NOT include: [things to avoid]
- If unsure, [fallback instruction]
- Maximum length: [limit]
Format: [exact format specification]
Validate before delivering:
1. [Validation criterion 1]
2. [Validation criterion 2]
3. [Validation criterion 3]"
## Graceful Degradation Template
"[Task description]
If you cannot complete the full task:
1. Explain what information is missing
2. Provide whatever you CAN derive
3. List what additional info is needed
4. Give confidence level for partial results
Never guess or make up data."
## Retry Template
"The previous attempt had issues:
[Error details]
Please regenerate, ensuring:
- [Specific fix 1]
- [Specific fix 2]
Here's the original input:
[Input data]"
## Boundary Testing Template
"[Task description]
Handle these edge cases:
- Empty input: [Expected behavior]
- Single item: [Expected behavior]
- Invalid input: [Expected behavior]
- Large input: [Expected behavior]
Show solutions for each case."Console Output
Error Recovery Templates
## Defensive Prompt Template
"[Task description]
Requirements:
- [Specific requirements]
IMPORTANT constraints:
- Do NOT include: [things to avoid]
- If unsure, [fallback instruction]
- Maximum length: [limit]
Format: [exact format specification]
Validate before delivering:
1. [Validation criterion 1]
2. [Validation criterion 2]
3. [Validation criterion 3]"
## Graceful Degradation Template
"[Task description]
If you cannot complete the full task:
1. Explain what information is missing
2. Provide whatever you CAN derive
3. List what additional info is needed
4. Give confidence level for partial results
Never guess or make up data."
## Retry Template
"The previous attempt had issues:
[Error details]
Please regenerate, ensuring:
- [Specific fix 1]
- [Specific fix 2]
Here's the original input:
[Input data]"
## Boundary Testing Template
"[Task description]
Handle these edge cases:
- Empty input: [Expected behavior]
- Single item: [Expected behavior]
- Invalid input: [Expected behavior]
- Large input: [Expected behavior]
Show solutions for each case."Code Visualization Tips
- Create a decision tree for error handling: What error? → What caused it? → How to fix?
- Draw a flowchart showing the retry logic workflow.
- Create a checklist of common errors and their prevention strategies.
Professional Tips & Tricks
- Always define what 'success' looks like before generating content.
- For critical content, include validation criteria in every prompt.
- Track which errors occur most frequently — they become prevention items.
Python Code Judge & Practice Arena
LeetCode StyleRun real Python 3.12 WebAssembly code directly in your browser against automated test suites.
Error Recovery Exercise
Test Your Knowledge
Instant feedbackQuick Check: Error Recovery & Edge Case Handling
Up next · Continue learning
Prompting for Code Generation
Write effective prompts for generating, debugging, and refactoring code across programming languages.