This prompt is designed for developers and tech leads who need to audit a pull request diff for error handling gaps. It targets three high-risk patterns: missing error handling on operations that can fail, exceptions that are caught and silently swallowed, and overly broad catch blocks that mask specific failure modes. Use this prompt in CI/CD pipelines as a pre-merge gate, during manual code review to catch what human eyes often skip, or as part of a security and reliability review checklist. The prompt assumes you have a unified diff as input and that the code is in a language with structured exception handling.
Prompt
Error Handling Adequacy Review Prompt

When to Use This Prompt
Understand the ideal use cases, required inputs, and critical limitations for the Error Handling Adequacy Review Prompt.
The ideal input is a git diff output or a unified diff file that captures the exact changes under review. The prompt works best when the diff is scoped to a single logical change, as large, multi-concern diffs can dilute the model's focus and produce noisier findings. You should configure the [RISK_LEVEL] placeholder to match your team's tolerance—setting it to strict will flag more potential issues, including unhandled promises in async code, while relaxed will focus only on the most obvious gaps. The [CONSTRAINTS] placeholder allows you to inject language-specific rules, such as "flag any function that returns a Result type without a caller check" or "ignore error handling inside test files."
This prompt does not replace human judgment for critical paths, nor does it verify that the suggested remediation patterns are semantically correct for the specific codebase. It may produce false positives in code that uses non-standard error propagation patterns or frameworks with centralized exception handlers. Always require human approval for findings marked critical or high severity before merging. Do not use this prompt as the sole gate for security-sensitive or safety-critical code paths—pair it with static analysis tools and manual review for those contexts.
Use Case Fit
Where the Error Handling Adequacy Review Prompt works well, where it falls short, and what you need before running it.
Good Fit: Backend Service PRs
Use when: reviewing diffs for backend services, API handlers, or data access layers where unhandled exceptions cause cascading failures. Guardrail: Pair with integration test results to confirm the model's remediation suggestions don't introduce new failure modes.
Bad Fit: Framework Boilerplate
Avoid when: the diff consists entirely of framework-generated scaffolding, configuration files, or third-party library wrappers where error handling patterns are predetermined. Guardrail: Pre-filter diffs to exclude paths like /generated/ or /vendor/ before running the prompt.
Required Input: Full Diff Context
What to watch: The prompt needs the complete unified diff with surrounding function signatures to distinguish between intentional broad catches and missing handlers. Guardrail: Always include at least 5 lines of context above and below each changed block. Truncated diffs produce false positives.
Operational Risk: Language-Specific Blind Spots
What to watch: The model may miss language-specific error handling idioms, such as Go's explicit error returns, Rust's Result types, or Python's context managers. Guardrail: Include a language-specific error handling reference in the prompt's [CONSTRAINTS] section with examples of acceptable patterns.
Operational Risk: Over-Reporting Noise
What to watch: The prompt can flag every catch (Exception) as a finding, overwhelming reviewers with low-value noise. Guardrail: Add a severity threshold in the output schema that distinguishes critical unhandled paths from style suggestions. Route only severity: critical findings to blocking review.
Required Input: Exception Taxonomy
What to watch: Without guidance on which exception types matter, the model treats all exceptions equally. Guardrail: Provide a domain-specific exception taxonomy in [CONTEXT] that maps exception types to severity levels and expected handling patterns for your codebase.
Copy-Ready Prompt Template
A reusable prompt template for reviewing a code diff to identify missing or inadequate error handling, producing a structured list of findings with severity and remediation patterns.
The following prompt template is designed to be pasted directly into your AI system or prompt management platform. It instructs the model to act as a senior code reviewer focused exclusively on error handling adequacy. The template uses square-bracket placeholders that you must replace with real values before execution. Do not leave any placeholder unresolved in production; the model will treat them as literal instructions and produce unreliable output.
textYou are a senior software engineer conducting a focused code review on error handling. Your only task is to identify missing, inadequate, or overly broad error handling in the provided code diff. ## INPUT Code Diff:
[CODE_DIFF]
codeLanguage: [LANGUAGE] Context (optional): [CONTEXT] ## CONSTRAINTS - Only report findings related to error handling. Do not comment on naming, style, performance, or logic unless it directly impacts error handling correctness. - For each finding, reference the specific file path and line range from the diff. - If no error handling issues are found, return an empty findings list. Do not fabricate issues. - Do not suggest changes that would alter the intended business logic. - If the diff contains test files, review them for missing error-path test coverage. ## OUTPUT_SCHEMA Return a valid JSON object with this exact structure: { "summary": "A one-sentence summary of the overall error handling posture of this diff.", "findings": [ { "severity": "critical|high|medium|low", "category": "missing_handler|swallowed_exception|overly_broad_catch|empty_catch|missing_log_context|unhandled_promise|missing_rollback|missing_user_feedback|missing_test_coverage", "file": "path/to/file.ext", "line_range": "L12-L18", "description": "What is wrong and why it matters.", "suggested_fix": "A concrete code example showing the recommended pattern.", "current_code_snippet": "The problematic code from the diff." } ] } ## RISK_LEVEL This review is for [RISK_LEVEL] risk code. Adjust severity thresholds accordingly: - low: Only flag missing handlers that could cause data loss or crashes. - medium: Flag swallowed exceptions, empty catch blocks, and missing log context. - high: Flag everything including overly broad catch blocks, missing rollback logic, and missing user-facing error messages. ## EXAMPLES Example finding for a swallowed exception: { "severity": "high", "category": "swallowed_exception", "file": "src/payment/processor.ts", "line_range": "L45-L48", "description": "Payment processing exception is caught and silently ignored. A failed charge will appear to succeed, causing revenue loss and customer confusion.", "suggested_fix": "try { await chargeCustomer(); } catch (error) { logger.error('Charge failed', { orderId, error }); throw new PaymentFailedError('Unable to process payment', { cause: error }); }", "current_code_snippet": "try { await chargeCustomer(); } catch (e) {}" }
To adapt this template, replace the placeholders with real data. [CODE_DIFF] should contain the full unified diff output. [LANGUAGE] helps the model apply language-idiomatic error handling patterns (e.g., try/catch for JavaScript, Result<T, E> for Rust). [CONTEXT] is optional but valuable for providing module purpose, known failure modes, or team conventions. [RISK_LEVEL] directly controls the strictness of the review; use high for payment, auth, or data mutation code, and low for internal tooling or non-critical paths. After pasting, validate that the model output conforms to the OUTPUT_SCHEMA before ingesting it into your review tool. If the output fails schema validation, retry with a stricter temperature setting or add a repair step using the schema error message as feedback.
Prompt Variables
Required inputs for the Error Handling Adequacy Review Prompt. Each placeholder must be populated before the prompt is sent to the model. Missing or malformed inputs are the most common cause of false negatives in error-handling review.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[DIFF] | The complete unified diff or code change to review for error handling gaps | git diff main...feature/retry-logic | Must be non-empty plain text. Validate with a minimum character count (>50). Reject binary diffs or merge conflict markers. |
[LANGUAGE] | The programming language or runtime context for selecting appropriate error handling patterns | Python 3.11 | Must match a known language identifier. Use a lookup table to map to language-specific patterns (try/except, Result<T>, ?, etc.). Reject unknown or ambiguous values. |
[FRAMEWORK] | Optional framework or library context that defines expected error handling conventions | FastAPI 0.100 | Null allowed. If provided, validate against a known framework list. Framework-specific patterns (middleware, interceptors) are applied only when this is set. |
[SEVERITY_THRESHOLD] | Minimum severity level to include in findings. Lower-severity issues are filtered out | medium | Must be one of: low, medium, high, critical. Validate with enum check. Default to medium if null. Controls output volume and noise. |
[CODEBASE_CONTEXT] | Optional surrounding codebase context for understanding custom error types, utility functions, or existing error handling patterns | error_utils.py contents or custom exception hierarchy | Null allowed. If provided, must be plain text under 8000 tokens. Improves accuracy for custom error wrapping and logging conventions. Truncate if over limit. |
[EXISTING_LINT_RULES] | Optional list of existing linter or static analysis rules already enforced, to avoid duplicate findings | ['try-except-raise', 'bare-except'] | Null allowed. If provided, must be a JSON array of rule IDs. Findings matching these rules are suppressed or marked as 'already enforced by linting' to reduce noise. |
[REVIEW_FOCUS] | Optional scoping instruction to focus review on specific error handling categories | swallowed exceptions, missing retry logic | Null allowed. If provided, must be a comma-separated string matching known categories: swallowed exceptions, bare except, missing retry, resource cleanup, error propagation, logging gaps, timeout handling, null safety. Limits review scope. |
Implementation Harness Notes
How to wire the Error Handling Adequacy Review Prompt into a CI/CD pipeline or code review tool with validation, retries, and human approval gates.
This prompt is designed to be called programmatically as part of a pull request review pipeline. The primary input is a unified diff, typically obtained from a version control system like Git. The application layer should extract the diff from the PR event, inject it into the [DIFF] placeholder, and handle the structured JSON output. Because the analysis is static and non-interactive, this prompt is well-suited for a single-turn, zero-temperature call to a capable model like GPT-4o or Claude 3.5 Sonnet. The model should be instructed to produce JSON only, without markdown fences, to simplify parsing.
A robust harness must validate the model's output against a strict JSON schema before any findings are posted as review comments. The schema should enforce that each finding object contains a line_number (integer), severity (enum of 'critical', 'high', 'medium', 'low'), category (string), description (string), and suggestion (string). If the output fails schema validation, implement a retry loop with a maximum of two attempts. On a retry, feed the raw output and the validation error message back to the model with a correction instruction. If validation fails after retries, the harness should log the failure and alert the development team rather than posting a partial or malformed review.
For high-risk repositories, integrate a human approval gate for all 'critical' severity findings. The harness should post lower-severity findings as standard inline review comments but flag critical findings in a separate, blocked state that requires a tech lead to acknowledge before the PR can be merged. Log every prompt call with a unique trace ID, capturing the input diff hash, the raw model output, the validation result, and the final posted findings. This audit trail is essential for debugging prompt drift, evaluating false positive rates, and iterating on the prompt template itself. Avoid wiring this prompt to automatically reject or close a PR; its role is to inform human decision-making, not to replace it.
Expected Output Contract
Defines the required JSON structure for the Error Handling Adequacy Review output. Use this contract to validate the model's response before integrating it into a CI/CD pipeline or review dashboard.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
findings | Array of objects | Array must be present; can be empty if no issues found. Schema check: validate each element against the finding object contract. | |
findings[].id | String (kebab-case) | Must match pattern | |
findings[].severity | Enum: critical, high, medium, low | Must be one of the four allowed values. Case-sensitive check. | |
findings[].file_path | String (relative path) | Must be a non-empty string. Existence check: verify the path exists in the diff context provided to the prompt. | |
findings[].line_range | String (e.g., 'L45-L52') | Must match pattern | |
findings[].category | Enum: swallowed_exception, empty_catch, broad_catch, missing_handling, unsafe_finally, resource_leak | Must be one of the six allowed values. Case-sensitive check. | |
findings[].description | String | Must be a non-empty string between 20 and 500 characters. Length check. | |
findings[].remediation | String | Must be a non-empty string between 20 and 1000 characters. Must not be identical to the description field. Similarity check: cosine similarity < 0.8. |
Common Failure Modes
When reviewing error handling in a diff, these are the most common failure modes that cause the prompt to produce useless or misleading results. Each card explains what breaks and how to guard against it.
False Positives on Intentional Broad Catches
What to watch: The prompt flags every generic catch (Exception) as a defect, even when it's intentional (e.g., top-level event loop guards, logging wrappers, or cleanup blocks where the specific exception type doesn't change behavior). This floods the review with noise and erodes trust. Guardrail: Add a [CONSTRAINTS] section instructing the model to skip catches that immediately log, rethrow, or run resource cleanup. Require the model to explain why a broad catch is risky before flagging it, and provide a severity of LOW for cases with clear justification.
Missing Context for Custom Error Handling Frameworks
What to watch: The model doesn't understand your team's custom error handling middleware, result types, or exception hierarchy. It suggests wrapping errors in standard library types that break your existing patterns, or it misses gaps because it doesn't recognize your Result<T, E> monad as error handling. Guardrail: Always provide a [CONTEXT] block with your project's error handling conventions, custom base exception classes, and result-type patterns. Include a few examples of correct usage from your codebase as few-shot demonstrations.
Swallowed Exceptions in Async Boundaries
What to watch: The prompt misses exception swallowing in fire-and-forget async calls, unawaited tasks, or background thread work. These are structurally invisible in a line-by-line diff because the error handling looks present but the control flow doesn't actually propagate exceptions. Guardrail: Add a specific instruction to inspect async call sites for missing await, unhandled promise rejections, or Task.Run without continuation error handling. Pair this prompt with a concurrency-specific review prompt for high-risk changes.
Overlooking Error Information Loss
What to watch: The prompt focuses on whether an error is caught but ignores whether the original error context (stack trace, inner exception, error code) is preserved. It approves throw new AppException('Something went wrong') that discards the original exception, making debugging impossible. Guardrail: Add an output field for information_loss that checks whether the original exception is passed as an inner exception, logged with its stack trace, or included in the error response. Flag any rethrow that drops the original exception as HIGH severity.
Hallucinated Remediation Patterns
What to watch: The model confidently suggests a fix that doesn't compile, uses APIs that don't exist in your language version, or introduces a pattern that conflicts with your codebase's existing error handling strategy. Guardrail: Add a [CONSTRAINTS] block specifying the exact language, version, and available libraries. Require that all suggested fixes reference APIs that exist in the provided context. Add a post-processing validation step that checks suggested code against your project's imports and dependencies before surfacing it to the reviewer.
Ignoring Resource Cleanup in Error Paths
What to watch: The prompt checks that exceptions are caught but doesn't verify that resources (file handles, database connections, network sockets) are properly closed in error paths. It approves a try-catch that catches the exception but leaks the unclosed resource from the try block. Guardrail: Add a specific instruction to trace resource acquisition through error paths. Flag any try block that opens a resource without a corresponding finally, using, try-with-resources, or context manager that guarantees cleanup. This is especially critical for database transactions and file I/O.
Evaluation Rubric
Use this rubric to test the Error Handling Adequacy Review Prompt before integrating it into a CI/CD pipeline. Each criterion targets a specific failure mode observed in code review prompts.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Missing Catch Block Detection | Prompt identifies all functions with risky operations (I/O, parsing) that lack a try/catch or .catch() handler. | Output omits a function that throws or awaits a fallible operation without a surrounding error handler. | Run against a diff containing a known unhandled async function. Verify the finding appears with the correct line reference. |
Overly Broad Catch Clause | Prompt flags catch blocks that handle | Output approves a generic catch block that swallows critical errors like | Provide a diff with |
Swallowed Exception Detection | Prompt identifies empty catch blocks or blocks that only log without re-throwing or setting an error state. | Output marks a completely empty | Inject a diff with an empty except block. Confirm the finding is present and categorized as 'High' severity. |
Resource Cleanup in Error Paths | Prompt notes missing | Output focuses only on the happy path and ignores a file handle opened before a try block that is not closed on exception. | Use a diff where a file stream is created but only closed in the main logic, not in the catch or finally block. |
Specific Remediation Pattern | Each finding includes a concrete, idiomatic fix suggestion (e.g., 'Use context manager', 'Add specific except clause'). | Suggestions are generic ('Fix error handling') or propose patterns that don't match the language of the diff. | Parse the [FIX_SUGGESTION] field. Validate that it contains a language-specific keyword like |
False Positive Rate on Utility Code | Prompt does not flag utility functions that intentionally propagate errors or simple getters/setters. | Output flags a | Include a diff with a pure validation function that throws. The output should have zero findings for that specific function. |
Output Schema Validity | The generated JSON payload strictly matches the [OUTPUT_SCHEMA] with all required fields present. | The JSON fails to parse, or a finding object is missing the | Run a JSON schema validator against the raw model output. The test fails if the validator returns any errors. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Add strict JSON schema validation, retry logic on parse failure, and structured logging of every review result. Include a confidence score per finding and require the model to cite the exact catch block or missing handler location.
codeReturn a JSON array of findings. Each finding must include: - "file": string - "line": number - "pattern": "swallowed_exception" | "bare_except" | "missing_handler" | "overly_broad_catch" - "severity": "critical" | "high" | "medium" | "low" - "confidence": 0.0-1.0 - "evidence": excerpt from diff - "remediation": string - "cwe_id": string or null If no issues found, return {"findings": [], "summary": "..."}
Watch for
- Silent format drift when model returns markdown-wrapped JSON
- Missing "evidence" field on borderline cases
- Confidence scores that don't match finding quality

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us