Reliability engineers and test infrastructure teams use this prompt to audit a service's error handling robustness. The prompt instructs an AI coding agent to trace error propagation paths through source code, identify error conditions that lack test coverage, flag assertions with inadequate depth, and surface missing recovery validation. The output is a structured coverage gap report organized by error type, suitable for prioritization in a test remediation backlog.
Prompt
Error Handling Coverage Assessment Prompt Template

When to Use This Prompt
Understand the job-to-be-done, required context, and boundaries for the error handling coverage assessment prompt.
Use this prompt when you have access to source code, existing test files, and optionally coverage reports or production error logs. The prompt works best for services where error handling is explicit—try/catch blocks, error return values, status code branches, retry logic, circuit breakers, and fallback paths. It is less effective for codebases that rely on implicit error propagation through unchecked exceptions or panic-style error handling without structured recovery. Before running the prompt, ensure the AI coding agent has read access to the relevant source directories, test directories, and any coverage report files. If production error logs are available, include them to ground the analysis in real failure patterns rather than theoretical error paths alone.
Do not use this prompt for real-time incident response or for services where the codebase is unavailable for static analysis. This prompt performs a static audit of error handling coverage, not a runtime diagnosis of an active incident. It will not catch error conditions that arise from infrastructure failures, network partitions, or resource exhaustion unless those conditions are explicitly modeled in the code. For production incidents, use the Error Diagnosis and Runtime Investigation Prompts instead. For services where only compiled artifacts are available without source access, this prompt cannot perform meaningful analysis. Always review the output before committing to a remediation plan—the AI may flag error paths that are intentionally left untested due to platform guarantees or operational controls that are not visible in the codebase.
Use Case Fit
Where the Error Handling Coverage Assessment prompt delivers reliable value and where it introduces unacceptable risk. Use this to decide whether to deploy the prompt, add safeguards, or choose a different approach.
Strong Fit: Mature Monoliths and Well-Factored Services
Use when: auditing a codebase with clear error propagation paths, structured exception hierarchies, and existing test infrastructure. The prompt excels at tracing try/catch blocks, Result types, or error-return conventions through call graphs. Guardrail: Provide the prompt with a focused module or service boundary rather than an entire monorepo to keep analysis depth high and hallucination risk low.
Required Inputs: Symbol Graph and Test Suite Map
Risk: Without a structured call graph, symbol index, or test-to-function mapping, the model guesses at propagation paths and misses coverage gaps. Guardrail: Pre-process the repository with a static analysis tool (e.g., tree-sitter, ctags, or language server) and pass a pruned call graph plus test-to-source mapping as [CONTEXT]. Never rely on the model to build the graph from raw file contents alone.
Bad Fit: Dynamic or Conventionless Error Handling
Avoid when: the codebase uses ad-hoc error handling, string-based error checks, dynamic dispatch, or framework magic that obscures propagation paths. The prompt will produce a false sense of coverage by missing implicit error flows. Guardrail: Run a pre-scan for structured error types. If fewer than 70% of error paths use typed exceptions or discriminated unions, flag the analysis as low-confidence and require manual review.
Operational Risk: False Negatives in Recovery Paths
Risk: The prompt may report error paths as 'covered' when tests only verify the error is thrown, not that recovery logic (retries, circuit breakers, compensating transactions) works correctly. Guardrail: Add an explicit [CONSTRAINTS] field requiring the prompt to distinguish between 'error detection coverage' and 'error recovery coverage' in its output. Flag any path where recovery is untested as a critical gap.
Bad Fit: Safety-Critical or Regulated Systems Without Review
Avoid when: the system under audit handles safety-critical functions, financial settlement, or regulated data where missed error handling has compliance or safety consequences. Guardrail: The prompt output must be treated as a triage aid, not a compliance artifact. Require a human reliability engineer to sign off on every gap marked 'low risk' before closing. Never use this prompt as the sole evidence in an audit.
Strong Fit: Pre-Release Hardening Sprints
Use when: the team has dedicated time to harden a service before a major release. The prompt's structured gap report integrates well with a remediation backlog. Guardrail: Pair the prompt output with a test generation prompt from the sibling playbooks to close gaps immediately. Track the percentage of identified gaps that result in merged tests as a team metric.
Copy-Ready Prompt Template
A reusable prompt template for mapping error propagation paths and identifying untested error conditions across a codebase.
This template is designed to be pasted into your AI coding agent or LLM interface after replacing the square-bracket placeholders with concrete values. It instructs the model to act as a reliability engineer auditing a service's error handling surface. The prompt forces the model to reason about error propagation paths—how errors flow from their origin through callers, middleware, and recovery logic—and then cross-reference those paths against the existing test suite to find coverage gaps. Use this when you need a structured, evidence-backed assessment of where your error handling is brittle, not just a list of untested functions.
textYou are a senior reliability engineer auditing the error handling robustness of a service. Your task is to map error propagation paths through the codebase and identify error conditions that lack adequate test coverage, have insufficient assertion depth, or are missing recovery validation. ## INPUT - Source code files: [CODEBASE_FILES] - Test files: [TEST_FILES] - Test coverage report (optional): [COVERAGE_REPORT] - Service architecture description: [ARCHITECTURE_DESCRIPTION] - Known error types and their expected handling: [ERROR_CATALOG] ## OUTPUT_SCHEMA Produce a JSON object with the following structure: { "error_propagation_map": [ { "error_type": "string (e.g., TimeoutError, DatabaseConnectionError)", "origin_location": "string (file:line where error is raised or thrown)", "propagation_path": ["string (ordered list of callers, middleware, and handlers the error passes through)"], "recovery_points": ["string (locations where error is caught, retried, or transformed)"], "expected_behavior": "string (documented or inferred handling strategy)" } ], "coverage_gaps": [ { "error_type": "string", "gap_category": "UNTESTED_PATH | WEAK_ASSERTION | MISSING_RECOVERY_VALIDATION | UNVERIFIED_SIDE_EFFECT", "location": "string (file:line or function name)", "description": "string (what is missing and why it matters)", "severity": "CRITICAL | HIGH | MEDIUM | LOW", "suggested_test_scenario": "string (concrete test case description)" } ], "summary": { "total_error_paths_identified": "number", "total_coverage_gaps": "number", "critical_gaps": "number", "high_gaps": "number", "assessment_confidence": "HIGH | MEDIUM | LOW (based on codebase coverage and documentation completeness)" } } ## CONSTRAINTS - Only report gaps where you have concrete evidence from the provided code and test files. Do not speculate about hypothetical errors not present in the code. - For each gap, you MUST cite the specific source code location and the specific test file (or absence thereof) that supports your finding. - If a coverage report is not provided, state your confidence as MEDIUM or LOW and note that static analysis alone may miss runtime error paths. - Classify a gap as CRITICAL only if the error path involves data loss, corruption, security exposure, or unrecoverable service outage. - Do not flag error paths that are handled by framework-level middleware unless the middleware itself is untested or misconfigured. ## TOOLS You may use the following tools if available: - search_codebase: to find error raising, throwing, and catching patterns - read_file: to inspect specific source and test files - grep: to search for error type references across the codebase ## RISK_LEVEL: HIGH This assessment informs production reliability decisions. If you are uncertain about a gap, mark it with lower confidence rather than omitting it. Human review of all CRITICAL and HIGH severity gaps is required before remediation.
After pasting this template, replace each square-bracket placeholder with concrete data from your repository. The [CODEBASE_FILES] and [TEST_FILES] placeholders should include the relevant source and test file paths or contents. If you lack a formal coverage report, omit [COVERAGE_REPORT] but expect the model to flag lower confidence. The [ERROR_CATALOG] is optional but strongly recommended—it can be a list of known error types your service handles, drawn from documentation or prior incidents. For high-risk services, always pair this prompt's output with a human review step before acting on any CRITICAL or HIGH severity gap. Validate the output against the schema before integrating it into your reliability dashboard or remediation backlog.
Prompt Variables
Placeholders required by the Error Handling Coverage Assessment prompt. Validate each before sending to prevent hallucinated error paths or false coverage signals.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CODEBASE_PATH] | Root directory or repository identifier for the service under audit | services/payment-gateway | Must resolve to an existing directory or repo slug. Fail if path is empty or inaccessible. |
[ERROR_PROPAGATION_SCOPE] | Boundary for error path tracing: single function, module, service, or cross-service | module:src/handlers | Must match one of: function, module, service, cross-service. Reject ambiguous scopes. |
[TEST_SUITE_PATH] | Location of existing test files to analyze for coverage gaps | tests/unit, tests/integration | At least one path must exist and contain test files. Warn if no test files found. |
[ERROR_CATALOG_SOURCE] | Source of known error types: exception classes, error codes, or OpenAPI error responses | src/errors.py, openapi.yaml#/components/responses | Must point to a parseable file or schema location. Validate file exists and contains error definitions. |
[COVERAGE_REPORT_PATH] | Path to existing coverage data (lcov, cobertura, or JSON summary) | coverage/lcov.info | Optional. If provided, must be a valid coverage file format. Set to null if unavailable. |
[EXTERNAL_DEPENDENCY_MAP] | List of external services, databases, or APIs the audited code calls | ["stripe-api", "user-db", "redis-cache"] | Must be a JSON array of dependency names. Each entry should match a real dependency in the codebase. |
[ASSERTION_DEPTH_THRESHOLD] | Minimum number of assertions required per error path to count as adequately covered | 3 | Must be a positive integer. Default to 2 if not specified. Values above 10 require explicit justification. |
[OUTPUT_FORMAT] | Desired output structure: json, markdown-report, or sarif | json | Must be one of: json, markdown-report, sarif. Reject unknown formats. |
Implementation Harness Notes
How to wire the Error Handling Coverage Assessment prompt into a production reliability workflow.
This prompt is designed to be integrated into a code analysis pipeline, not run as a one-off chat interaction. The primary integration point is a CI/CD or scheduled audit job that triggers when coverage reports, static analysis results, or new code diffs are available. The harness must supply the prompt with structured inputs—source code, existing test files, and error propagation metadata—and then parse, validate, and route the structured output for action.
Input Assembly: Before calling the model, assemble the [SOURCE_CODE] and [TEST_CODE] blocks by walking the repository's abstract syntax tree (AST) to extract functions with throw, raise, reject, or error-return patterns. For each error site, trace the call graph to identify upstream callers and downstream recovery points. Package this as a structured [ERROR_PROPAGATION_MAP] with fields: error_type, origin_file, propagation_path, and recovery_point. The [EXISTING_TEST_COVERAGE] input should be a machine-readable coverage report (e.g., lcov or JaCoCo XML) filtered to the files in scope. Model Selection: Use a model with strong code reasoning and large context windows (e.g., Claude 3.5 Sonnet, GPT-4o, or Gemini 1.5 Pro). The prompt's structured output requirement and multi-file reasoning demand a capable frontier model; smaller or local models may produce malformed JSON or miss cross-file error propagation paths.
Output Validation and Routing: The prompt requests a JSON array of gap objects. Implement a post-processing validator that checks: (1) every error_type references a real exception class or error code in the codebase, (2) every file_path exists in the repository, (3) severity is one of the allowed enum values, and (4) suggested_test_scenario is non-empty. Reject and retry malformed outputs once; if the retry also fails, log the failure and alert the reliability team. Valid outputs should be written to a gap tracking system (e.g., a GitHub Issue with the error-handling-coverage label, a Jira ticket, or a dedicated dashboard database). Each gap should include a unique fingerprint (hash of error_type + file_path + function_name) to enable deduplication across runs and track remediation over time.
Human Review and Escalation: Gaps with severity: critical—especially those in authentication, data persistence, or network boundary code—should automatically trigger a notification to the service owner and create a high-priority ticket. Do not auto-generate patches from this prompt's output; the suggested test scenarios are starting points for a human engineer to write precise, context-aware tests. Run this assessment on every major release branch and on a weekly schedule for the main branch. Track gap counts over time as a reliability metric: a rising trend in uncovered error paths signals that error handling discipline is slipping and warrants a team-level discussion.
Expected Output Contract
Defines the structure, types, and validation rules for the error handling coverage assessment report. Use this contract to parse, validate, and store the model output before surfacing it to downstream systems or human reviewers.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
report_summary.total_error_paths | integer | Must be >= 0. Parse as int. Fail if negative or non-numeric. | |
report_summary.covered_error_paths | integer | Must be <= total_error_paths. Parse as int. Fail if negative or non-numeric. | |
report_summary.coverage_percentage | number | Must be between 0.0 and 100.0 inclusive. Parse as float. Fail if NaN or out of range. | |
findings[].error_type | string | Must be non-empty string. Must match one of the categories listed in the prompt's [ERROR_CATEGORIES] input if provided, otherwise free-text but required. | |
findings[].propagation_path | string | Must be non-empty string. Should contain a call chain or file reference. Schema check: reject if null or whitespace-only. | |
findings[].test_coverage_status | enum: covered | uncovered | partial | Must be exactly one of the three enum values. Case-sensitive. Reject any other value. | |
findings[].existing_tests | array of strings | If present, each element must be a non-empty string. If coverage_status is 'covered' or 'partial', this field should be present and non-empty; flag for human review if missing. | |
findings[].recovery_validated | boolean | Must be true or false. If coverage_status is 'covered' and recovery_validated is false, flag as 'assertion depth warning' for human review. |
Common Failure Modes
When auditing error handling coverage, these failures degrade report quality and trust. Each card pairs a common failure with a concrete guardrail you can embed in your evaluation harness.
Hallucinated Error Paths
What to watch: The model invents error conditions or propagation paths that don't exist in the codebase, producing a coverage report that looks thorough but is fabricated. This happens most often when the model lacks direct access to callee implementations or when error handling relies on implicit conventions. Guardrail: Require every reported error path to cite a specific file, line range, and code snippet. Add a validator that checks cited locations exist in the repository before accepting any finding.
Missed Silent Error Swallowing
What to watch: The model identifies explicit catch blocks but misses error suppression patterns like empty catch bodies, logged-and-ignored errors, or return-value discarding. These are the highest-risk gaps because they hide failures in production. Guardrail: Add a dedicated pass that searches for catch blocks with empty bodies, discarded error returns, and error logs without corresponding recovery or escalation. Flag these separately from missing catch blocks.
Assertion Depth Blindness
What to watch: The model reports that an error condition is tested because a test exercises the code path, but the test only checks that no exception is thrown—it never asserts on recovery behavior, state consistency, or error response content. Guardrail: Require the assessment to distinguish between 'path exercised' and 'behavior verified.' For each reported gap, include the specific assertion that should exist but doesn't, such as state rollback, metric emission, or error response field validation.
Cross-Service Propagation Gaps
What to watch: The model analyzes error handling within a single service but misses gaps where errors propagate across service boundaries—untranslated error codes, leaked internal details, missing retry policies, or broken circuit breaker patterns. Guardrail: Extend the analysis to include service boundary code paths. For each cross-service call, check that error translation, retry logic, and fallback behavior are explicitly covered. Flag any boundary where the error type changes without a corresponding test.
Recovery Path Absence
What to watch: The model focuses on whether errors are caught but ignores whether the system recovers correctly after the error—state corruption, resource leaks, partial writes, or broken invariants that persist after the error handler runs. Guardrail: For each critical error path, require the assessment to check post-recovery state: Are transactions rolled back? Are locks released? Are metrics and traces complete? Flag any error handler that lacks a test verifying the system returns to a valid state.
Context Window Truncation
What to watch: Large codebases exceed the model's context window, causing the assessment to silently skip files or functions at the edges of the provided context. The resulting report looks complete but has systematic blind spots. Guardrail: Chunk the codebase by service or module and run the assessment independently per chunk. Include a manifest of all files analyzed in each chunk. Cross-reference the manifest against the repository file list and flag any unanalyzed files before merging results.
Evaluation Rubric
Score each dimension on a 1–5 scale before shipping the Error Handling Coverage Assessment prompt. Use the Test Method column to automate checks in your eval harness.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Error Path Completeness | All call paths in [CODEBASE_CONTEXT] that can throw or propagate errors are enumerated in the output | Output misses documented exception types or error return values visible in the code | Diff output error paths against static analysis call graph; flag any path with a throw/return err not listed |
Coverage Gap Accuracy | Each gap correctly identifies a test file or test case that should exist but does not | Gap references a test that already exists in [TEST_SUITE_MAP] or invents a non-existent error condition | Cross-reference each gap's target function and error type against the test suite index; fail if match found |
Assertion Depth Assessment | For each covered error path, assertion depth is rated (none/status-only/message/behavior/recovery) with evidence from existing test code | Rating contradicts the actual assertions visible in the referenced test; recovery validation claimed where none exists | Parse referenced test file for assert/expect calls on the error path; compare against the assigned depth rating |
Recovery Validation Identification | All error paths where recovery logic exists in code are flagged with a recovery validation gap if no test exercises the recovery path | Recovery logic is present in source but output marks recovery validation as complete or omits the gap | For each try-catch or error-handling branch with retry/fallback logic, verify output either cites a test exercising it or flags a gap |
Source Grounding | Every finding includes a file path, line range, or function signature from [CODEBASE_CONTEXT] as evidence | Finding contains unsupported claims without code references or cites lines that do not contain the claimed error path | Sample 20% of findings; validate each reference points to code that matches the described error condition |
Severity Classification Consistency | Gaps are classified (Critical/High/Medium/Low) using consistent criteria: data loss risk, user-facing impact, recovery absence | Two gaps with identical characteristics receive different severity ratings; low-impact cosmetic error paths rated Critical | Extract severity rules from [SEVERITY_RUBRIC]; apply to a held-out set of labeled gaps and measure agreement |
Output Schema Compliance | Output matches [OUTPUT_SCHEMA] exactly: all required fields present, no extra fields, correct types | Missing required fields, null values where non-nullable, or extra undocumented fields in the JSON output | Validate output against [OUTPUT_SCHEMA] using a JSON schema validator; fail on any violation |
Actionability of Recommendations | Each gap includes a concrete test scenario description with suggested assertion type and test location | Recommendations are vague (add tests), circular (test error handling), or impossible to implement from the description | Human review or LLM-as-judge: can a developer write the test from the recommendation alone without re-analyzing the code? |
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
Start with the base prompt and a single service or module. Remove structured output requirements initially—let the model return free-text findings first. Use a smaller codebase slice (one directory, one error handling pattern) to validate the approach before scaling.
Simplify the prompt to focus on one error type at a time:
codeAnalyze [MODULE_PATH] for error handling gaps. Focus only on [ERROR_TYPE]. List uncovered error paths with file:line references.
Watch for
- Missing file:line grounding—prototype outputs may be vague
- Over-reporting of low-severity gaps without prioritization
- No distinction between dead code and genuinely uncovered error paths
- Model may invent error paths not present in the codebase

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