Error Handling Prompt (ChatGPT)
Error handling is frequently added as an afterthought, resulting in inconsistent patterns and swallowed exceptions. This prompt designs the complete error handling strategy before writing code — typed errors, logging context, and user-facing messages — ensuring a consistent approach throughout the codebase. This variant is formatted for ChatGPT: Optimised for GPT-4o and GPT-4 Turbo. Uses markdown formatting and system/user message separation.
## System
You are an expert AI assistant. Respond using clear markdown formatting.
## User
You are a senior software engineer specialising in reliability and fault tolerance.
Add comprehensive error handling to the following {{language}} code.
Current code:
```{{language}}
{{code}}
```
Error handling requirements:
- Catch and handle all potential exceptions
- Distinguish between recoverable and unrecoverable errors
- Log errors with sufficient context (correlation ID, user ID, operation name) — never log sensitive data
- Return user-friendly error messages (not stack traces)
- Use typed/custom error classes where appropriate
- {{additional_requirements}}
For each error scenario, specify:
1. What triggers the error
2. How it is caught
3. What is logged (and at what log level)
4. What is returned to the caller
After the refactored code, provide a list of all error scenarios handled.Variables
{{language}}Programming language, e.g., TypeScript, Python, Go{{code}}The code that needs error handling added{{additional_requirements}}Extra constraints, e.g., "retry transient errors up to 3 times", or "None"Example
language: TypeScript
additional_requirements: Retry transient network errors up to 3 times
code:
async function fetchUserData(userId: string) {
const response = await fetch(`https://api.example.com/users/${userId}`);
const data = await response.json();
return data;
}class UserNotFoundError extends Error {
constructor(userId: string) {
super(`User ${userId} not found`);
this.name = 'UserNotFoundError';
}
}
async function fetchUserData(userId: string, attempt = 1): Promise<UserData> {
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (response.status === 404) throw new UserNotFoundError(userId);
if (!response.ok) {
if (attempt < 3 && response.status >= 500) {
await delay(200 * attempt);
return fetchUserData(userId, attempt + 1);
}
throw new Error(`API error: ${response.status}`);
}
return response.json() as Promise<UserData>;
} catch (err) {
logger.error({ userId, attempt, err }, 'fetchUserData failed');
throw err;
}
}Related Tools
FAQ
- Should I catch all errors or let them propagate?
- Only catch errors you can handle meaningfully. Catching everything and swallowing errors is worse than letting them propagate. Catch at the boundary where you can provide a useful response (e.g., the route handler) and let internal functions throw.
- How do I create custom error types?
- In TypeScript/JavaScript, extend the Error class and set the name property. In Python, extend Exception. Custom error types let callers use instanceof checks to handle specific errors differently without parsing message strings.
- What should I log in an error handler?
- Log the error message, stack trace, and enough context to reproduce the issue: request ID, user ID (not PII), operation name, and relevant input parameters (redacted). Never log passwords, tokens, or credit card numbers.
Related Prompts
Error handling is frequently added as an afterthought, resulting in inconsistent patterns ...
Error Handling Prompt (Claude)Error handling is frequently added as an afterthought, resulting in inconsistent patterns ...
Error Handling Prompt (Gemini)Error handling is frequently added as an afterthought, resulting in inconsistent patterns ...
Error Handling Prompt (LLaMA / Ollama)Error handling is frequently added as an afterthought, resulting in inconsistent patterns ...
Debugging Assistant PromptMost debugging sessions fail not because the fix is hard to find but because the problem i...
Code Review PromptThis prompt structures code reviews into five clear categories so the AI produces actionab...