Inferensys

Prompt

Error-Handling Code Example Prompt Template

A practical prompt playbook for generating production-grade error-handling code examples for API documentation. Covers try/catch, retry logic, and graceful degradation patterns.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Identify the right scenarios for generating error-handling code examples and recognize when this prompt is the wrong tool.

This prompt is for documentation engineers and DevRel teams who need to generate realistic, runnable code examples that demonstrate proper error handling for API calls. Use it when your documentation must show developers how to handle network failures, invalid responses, rate limits, and unexpected exceptions without swallowing errors silently. The ideal user already has a defined API contract and error schema—this prompt translates that contract into a complete, annotated code block that covers both expected error types (4xx, 5xx) and unexpected failures (network timeouts, DNS resolution), including retry logic where appropriate.

Do not use this prompt for generating happy-path-only examples, security-specific auth flows, or framework-specific middleware configuration. It is not designed for producing code that demonstrates a single successful API call without error branches, nor for generating OAuth token exchange logic or Express middleware error handlers. The prompt assumes the target API contract and error schema are already defined—if you are still designing the error response format or haven't finalized which status codes each endpoint returns, resolve those design decisions first. Similarly, if your documentation needs a complete SDK method reference or a full quickstart guide, pair this prompt with the SDK Quickstart or API Endpoint Usage Example prompts rather than overloading it.

Before using this prompt, gather the API endpoint specification, the error response schema for each status code, the retry policy (including backoff strategy and max attempts), and the target language and runtime version. The prompt works best when you provide concrete error payloads rather than abstract descriptions—real JSON error bodies produce more accurate catch blocks and conditional logic. After generation, validate the output by running the code against a mock server that returns each documented error type, and verify that no exception goes uncaught and that retry logic respects rate-limit headers. If the generated example will appear in production documentation, add a human review step to confirm the error-handling pattern matches your team's conventions and doesn't introduce resource leaks or infinite retry loops.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Error-Handling Code Example Prompt Template delivers value and where it introduces risk. Use these cards to decide whether this prompt fits your current documentation task before you invest in the harness.

01

Good Fit: Documenting Failure Modes

Use when: you need to show developers exactly how to catch, classify, and respond to specific error codes from your API. Guardrail: always pair the generated example with a live test harness that verifies the error is actually triggerable and the catch block executes.

02

Bad Fit: Undocumented or Unstable Errors

Avoid when: the target API's error surface is undocumented, unstable, or varies unpredictably across environments. Risk: the prompt will hallucinate plausible but incorrect error classes and status codes. Guardrail: require a validated error catalog as input; if none exists, generate only the structural pattern and mark error types as placeholders.

03

Required Input: Error Catalog Schema

What to watch: without a structured list of error types, codes, retryability flags, and recovery actions, the model invents error scenarios that mislead developers. Guardrail: provide an [ERROR_CATALOG] input with at minimum: error code, HTTP status, retryable boolean, and recommended user action for each documented failure mode.

04

Operational Risk: Silent Exception Swallowing

What to watch: generated examples may catch broad exception types and log without re-raising, teaching developers anti-patterns that hide production failures. Guardrail: add an explicit [CONSTRAINTS] block requiring that every catch block either handles the error fully, re-raises, or escalates—and run a static analysis lint rule in the eval harness to enforce this.

05

Operational Risk: Stale Retry Logic

What to watch: retry examples hardcode backoff intervals, max attempts, or retryable status codes that drift from the live API's rate-limit headers and documented policy. Guardrail: the eval harness must parse the API's current Retry-After and rate-limit headers, then assert the generated example respects them—flagging any mismatch before publication.

06

Variant: Language-Specific Idioms

What to watch: a single error-handling pattern translated literally across languages produces non-idiomatic code (e.g., exception handling in Go vs. try/catch in JavaScript). Guardrail: use the [TARGET_LANGUAGE] variable to switch error-handling paradigms, and include a language-specific style check in the eval harness that compares against community-standard patterns for that runtime.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt template for generating robust, production-style error-handling code examples for API calls.

This prompt template is designed to generate a single, runnable code example that demonstrates robust error handling for a specific API endpoint. Unlike basic 'happy path' snippets, this prompt forces the model to produce code that accounts for real-world failure modes, including network issues, server errors, and client mistakes. The output is a complete, self-contained code block with inline comments, ready for a developer to copy, adapt, and integrate into a larger application. The template uses square-bracket placeholders that you must replace with your specific API details, target language, and error-handling requirements before use.

text
Generate a complete, runnable code example in [LANGUAGE] that demonstrates robust error handling for calling the [API_ENDPOINT] endpoint using the [HTTP_CLIENT_OR_SDK] library. The example must cover the following error scenarios: [LIST_ERROR_SCENARIOS]. Include retry logic with exponential backoff and jitter for retryable errors [RETRYABLE_STATUS_CODES]. The code must never swallow exceptions silently. Every caught exception must either be logged with context, re-thrown with additional information, or handled with a documented fallback. Add inline comments explaining the purpose of each error handler. The output must be a single code block with no surrounding explanation. Use [LANGUAGE_VERSION]-idiomatic patterns and avoid deprecated APIs. The success response type is [SUCCESS_RESPONSE_TYPE] and the error response type is [ERROR_RESPONSE_TYPE]. [ADDITIONAL_CONSTRAINTS]

To adapt this template, start by replacing the core placeholders. For [LANGUAGE] and [LANGUAGE_VERSION], specify the exact target, such as Python and 3.11+. For [HTTP_CLIENT_OR_SDK], choose the specific library, like httpx or the openai Python SDK. The [LIST_ERROR_SCENARIOS] placeholder is critical; be explicit, for example: a 401 authentication error, a 429 rate limit with a Retry-After header, a 503 server error, and a network timeout. Define [RETRYABLE_STATUS_CODES] as a list like [429, 503]. The [SUCCESS_RESPONSE_TYPE] and [ERROR_RESPONSE_TYPE] placeholders should be filled with concrete types or structures, such as dict or MyAPIError. Use the [ADDITIONAL_CONSTRAINTS] field to enforce project-specific rules, like 'Do not use third-party retry libraries' or 'Use structured logging with structlog'. After generating the code, always validate it against your project's linting, security scanning, and testing harness before publishing it in documentation.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Error-Handling Code Example Prompt Template. Each placeholder must be populated before the prompt is sent to the model. Missing or malformed inputs are the most common cause of silent exception swallowing in generated examples.

PlaceholderPurposeExampleValidation Notes

[LANGUAGE]

Target programming language for the code example

Python 3.11

Must match a supported language identifier. Validate against a known list of languages. Reject ambiguous values like 'js' when 'Node.js 20' is required.

[API_OPERATION]

Description of the API call that can fail

POST /v1/charges with idempotency key

Must include the HTTP method, endpoint path, and at least one failure-relevant detail. Reject if only a method name is provided without the failure surface.

[ERROR_TYPES]

List of error categories the example must handle

NetworkTimeout, RateLimitExceeded, InvalidRequest, ServerError

Each entry must map to a known error class or status code range. Validate that at least one transient error and one non-retryable error are included. Reject if all errors are generic.

[RETRY_STRATEGY]

Retry policy to demonstrate in the example

Exponential backoff with jitter, max 3 retries

Must specify the backoff algorithm, max attempts, and whether jitter is included. Validate that max retries is a positive integer. Reject if the strategy would retry non-retryable errors.

[GRACEFUL_DEGRADATION]

Fallback behavior when the operation cannot succeed

Return cached result from last 24 hours or null with degraded=true flag

Must describe a concrete fallback action. Validate that the fallback does not silently return a success value. Reject if the fallback masks the failure from the caller.

[CONTEXT]

Surrounding code context where the example will be inserted

Inside an async request handler in a FastAPI route

Must describe the execution environment and calling context. Validate that the context is compatible with the target language. Reject if the context implies synchronous execution for an async example.

[OUTPUT_SCHEMA]

Expected structure of the generated code example

Single function with try/except blocks, inline comments, and a usage example in main

Must specify the required code elements. Validate that error handling is explicitly requested. Reject schemas that allow the model to omit catch blocks or error propagation.

PROMPT PLAYBOOK

Implementation Harness Notes

Wire this prompt into a documentation generation pipeline with validation, retries, and human review gates.

Wire this prompt into a documentation generation pipeline by calling it once per endpoint per language. Store the output as a raw code block in your documentation CMS. The prompt expects [API_OPERATION], [LANGUAGE], [SDK_CLIENT], [ERROR_CATALOG], and [ADDITIONAL_CONSTRAINTS] as inputs. Map these from your API spec, error code registry, and style guide before each invocation. For teams using OpenAPI, extract the operation ID, response schemas, and documented error codes programmatically to populate [ERROR_CATALOG] with the exact error shapes your API returns—don't let the model invent error types.

Before publishing, run the generated code through a syntax validator for the target language. Use pylint --errors-only for Python, ruby -c for Ruby, node --check for JavaScript, or the equivalent compiler/linter for your language. If the code references a real SDK, execute it against a mock server that returns both success and error responses to verify the error branches are reachable. The mock server must simulate at minimum: a 4xx client error with a structured error body, a 5xx server error, and a network timeout. Assert that the generated example catches each error type without swallowing exceptions silently and that retry logic (if present) respects the mock's Retry-After headers. Log every generated example with its prompt variables—operation ID, language, SDK version, and timestamp—for traceability when examples later break.

For high-risk APIs where incorrect error handling could cause data loss (write operations, deletion endpoints, financial transactions), require a human reviewer to approve the example before publication. Set a max token limit of 1500 for the output to prevent the model from generating overly verbose examples that bury the error-handling logic in boilerplate. If the output fails syntax validation, retry once with the error message appended to [ADDITIONAL_CONSTRAINTS]—for example, [ADDITIONAL_CONSTRAINTS]: Previous output failed Python syntax check: 'SyntaxError: invalid syntax at line 12'. Fix the syntax error while preserving the error-handling logic. If the retry also fails, flag the example for manual authoring and log the failure pattern to improve the prompt template over time.

IMPLEMENTATION TABLE

Expected Output Contract

Validation rules for the error-handling code example generated by the prompt. Use this contract to programmatically verify the output before publishing it in documentation.

Field or ElementType or FormatRequiredValidation Rule

code_block

String (fenced code block)

Parse check: Must contain exactly one fenced code block with a language identifier matching [LANGUAGE]. Block must not be empty.

error_scenario_coverage

Array of strings

Schema check: Must include at least one expected error type (e.g., network timeout, 4xx) and one unexpected error type (e.g., generic Exception). No silent except/pass blocks allowed.

retry_logic

Boolean or code pattern

Pattern check: If [RETRY_STRATEGY] is 'exponential_backoff', code must contain a backoff calculation with a max retry constant. If 'none', retry logic must be absent.

resource_cleanup

Code pattern

Static analysis: Must include finally block, context manager (with statement), or explicit close/disconnect for any opened connection, file handle, or client resource.

error_propagation

Code pattern

Pattern check: At least one error path must re-raise or return a structured error object. Swallowing exceptions with pass in an except block is a hard failure.

graceful_degradation

Code pattern or comment

Schema check: If [DEGRADATION_MODE] is not null, code must include a fallback path (e.g., cached response, default value, user notification) when the primary operation fails.

inline_comments

String (within code block)

Density check: If present, comments must explain why the error-handling decision was made, not what the code does. Comment-to-code ratio must not exceed 30%.

security_safety

Code pattern

Lint check: Must not contain hardcoded credentials, API keys, or tokens. Error messages must not leak stack traces, internal paths, or sensitive configuration values to the user or log output.

PRACTICAL GUARDRAILS

Common Failure Modes

Error-handling code examples fail in predictable ways that undermine documentation trust. Here are the most common failure modes and how to prevent them before publication.

01

Silent Exception Swallowing

What to watch: The generated example catches exceptions but only logs or ignores them without re-raising, propagating, or handling the failure state. Readers copy this pattern and ship code that hides errors. Guardrail: Require every catch block to either handle the error fully (retry, fallback, user message) or re-raise. Add an eval assertion that no catch block is empty or contains only a comment.

02

Overly Broad Exception Handling

What to watch: The example catches Exception, Throwable, or base exception classes instead of specific error types. This masks unexpected failures and makes debugging impossible. Guardrail: Enforce specific exception type handling in the prompt constraints. Add a static analysis check that flags generic catch clauses and requires at least one specific exception type per handler.

03

Missing Resource Cleanup in Error Paths

What to watch: The example opens connections, file handles, or streams but doesn't close them when an error occurs. The happy path cleans up, but exception paths leak resources. Guardrail: Require try-with-resources, context managers, defer, or finally blocks in the prompt template. Add a resource leak detection eval that traces open/close pairs through all code paths.

04

Retry Logic Without Backoff or Limits

What to watch: The example implements retry but uses fixed delays, no jitter, or infinite loops. This teaches readers to build thundering-herd problems or hung processes. Guardrail: Constrain the prompt to require exponential backoff with jitter, max retry count, and non-retryable error discrimination. Validate that the example terminates within a bounded number of attempts.

05

Error Messages Leaking Sensitive Data

What to watch: The example includes raw error responses, stack traces, or internal state in user-facing error messages. This creates information disclosure vulnerabilities in production. Guardrail: Add a security linting step that scans generated examples for stack traces, internal paths, raw API error bodies, and unredacted identifiers. Require sanitized user-facing messages.

06

Inconsistent Error Handling Across Languages

What to watch: When generating multi-language examples, one language handles errors idiomatically while another uses a generic pattern copied from the first language. Readers get non-idiomatic code that doesn't match their ecosystem. Guardrail: Include language-specific error handling conventions in the prompt (e.g., Go error returns, Rust Result types, Python context managers). Run language-specific style checks on each output variant.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the quality of generated error-handling code examples before shipping. Each criterion targets a specific failure mode common in documentation code samples.

CriterionPass StandardFailure SignalTest Method

Error Type Coverage

Example handles both expected errors (e.g., network timeout) and unexpected errors (e.g., null pointer) with distinct paths

All errors caught by a single generic catch block or unexpected errors are silently swallowed

Static analysis: count catch blocks and verify at least two distinct error types are handled differently

Exception Swallowing Prevention

No catch block is empty or contains only a comment; every caught error is logged, re-thrown, or wrapped

Empty catch block present or error is caught and discarded without any observable side effect

AST scan: flag any catch block with zero statements or only a comment

Resource Cleanup

Resources (connections, file handles, readers) are closed in finally blocks or via try-with-resources constructs

Resource opened in try block but not closed on exception path, causing a leak

Linter check: run resource-leak detection rule against the generated code

Retry Logic Correctness

Retry uses exponential backoff with jitter, respects a max retry limit, and does not retry on 4xx client errors

Retry loops infinitely, retries on 400-level status codes, or uses fixed-interval retry without jitter

Unit test: simulate a 429 response and verify backoff timing and retry count

Error Propagation Fidelity

Original error context (stack trace, status code, response body) is preserved when wrapping or re-throwing

Original exception is discarded and replaced with a generic message that loses root cause information

Code review: verify the original error object is passed as the inner exception or cause parameter

Graceful Degradation Path

Example shows a fallback action (cached response, default value, user notification) when the primary operation fails

Example terminates or returns null without indicating to the caller that degradation occurred

Behavioral test: run the example with a simulated failure and verify a non-null fallback output is produced

Logging Hygiene

Errors are logged at appropriate levels (ERROR for failures, WARN for retries) without exposing credentials or PII in log statements

Credentials, API keys, or user data appear in log output; or errors are logged at DEBUG level and lost in production

Log output scan: search for credential patterns and verify log level constants match severity

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add a strict [OUTPUT_SCHEMA] requiring structured JSON with language, error_scenarios, and code fields. Require each scenario to specify error_type, expected_behavior, recovery_action, and retry_strategy. Include a [CONSTRAINTS] block mandating: no bare except:, no hardcoded credentials, and explicit resource cleanup. Wire the output through a schema validator before publication.

Watch for

  • Schema drift when the model omits retry_strategy for non-retryable errors
  • Examples that catch Exception broadly instead of discriminating by error type
  • Missing finally or context-manager cleanup in resource-heavy examples
Prasad Kumkar

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.