Back to cookbook

ChatGPT Prompt to Debug an Error From a Stack Trace

2 views Updated
Share

A debug stack trace prompt gives ChatGPT, Claude, or Gemini the exact error message, the stack trace, and the relevant code so it can find the root cause instead of guessing from a vague description like "my app is broken." This is for developers who are stuck staring at a traceback, a failed CI job, or a production error log and want a model to narrow down what actually went wrong before they start changing code.

The prompt works because it forces structure: the full error text, the stack trace in order from where the exception was raised, the code around each relevant frame, and what the developer already tried. Models are good at pattern-matching known exception types and common causes (null references, off-by-one errors, async timing issues, type mismatches) when given this context, but they will hallucinate a plausible-sounding fix if the trace is incomplete or truncated.

Used well, the output is a ranked list of likely causes tied to specific lines, not a single confident guess. If the stack trace is long or spans multiple files, pasting it alongside a vague prompt wastes tokens and often gets cut off mid-context, so running it through a Token Optimizer first keeps the trace and surrounding code lean enough that nothing relevant gets dropped before the model sees it.

Prompt template

ROLE: You are an experienced [PROGRAMMING LANGUAGE] developer helping debug a runtime error.

CONTEXT:

  • Language/runtime: [LANGUAGE AND VERSION, e.g. Python 3.11, Node 20]

  • Framework/libraries involved: [FRAMEWORK NAMES AND VERSIONS]

  • What the code is supposed to do: [BRIEF DESCRIPTION OF THE FEATURE OR FUNCTION]

  • Error message and full stack trace: [PASTE FULL ERROR MESSAGE AND STACK TRACE HERE, TOP TO BOTTOM, UNEDITED]

  • Relevant source code (include every function/file named in the trace): [PASTE CODE FOR EACH FRAME IN THE STACK TRACE]

  • What I've already tried: [LIST ANY FIXES OR CHECKS ALREADY ATTEMPTED, OR WRITE "NOTHING YET"]

CONSTRAINTS:

  • Do not suggest a fix until you've identified the specific line and condition that triggers the exception
  • If the trace doesn't contain enough information to be certain, say so and list what additional information (logs, input values, config) would confirm the cause
  • Do not assume framework defaults that weren't stated — ask if a detail is missing rather than guessing

OUTPUT FORMAT:

  1. Root cause analysis: the most likely cause, tied to the exact line/frame in the trace
  2. Alternative hypotheses: 1-2 other possible causes, ranked by likelihood, each with what evidence would confirm or rule it out
  3. Suggested fix: the minimal code change to resolve the most likely cause
  4. Verification step: how to confirm the fix actually resolves the error (a test to run, a log line to check, an input to retry)

Example input

ROLE: You are an experienced Python developer helping debug a runtime error.

CONTEXT:

  • Language/runtime: Python 3.11

  • Framework/libraries involved: FastAPI 0.110, SQLAlchemy 2.0

  • What the code is supposed to do: fetch a user's order history by user_id and return it as JSON

  • Error message and full stack trace: Traceback (most recent call last): File "app/routers/orders.py", line 42, in get_order_history orders = db.query(Order).filter(Order.user_id == user_id).all() File "app/models/order.py", line 18, in repr return f"<Order {self.id} total={self.total.amount}>" AttributeError: 'NoneType' object has no attribute 'amount'

  • Relevant source code:

app/routers/orders.py

@router.get("/orders/{user_id}") def get_order_history(user_id: int, db: Session = Depends(get_db)): orders = db.query(Order).filter(Order.user_id == user_id).all() return orders

app/models/order.py

class Order(Base): id = Column(Integer, primary_key=True) user_id = Column(Integer) total = Column(Money, nullable=True)

def __repr__(self):
    return f"<Order {self.id} total={self.total.amount}>"
  • What I've already tried: confirmed user_id exists in the database and has orders

CONSTRAINTS:

  • Do not suggest a fix until you've identified the specific line and condition that triggers the exception
  • If the trace doesn't contain enough information to be certain, say so

OUTPUT FORMAT:

  1. Root cause analysis
  2. Alternative hypotheses
  3. Suggested fix
  4. Verification step

Example output

  1. Root cause analysis: The exception is raised in Order.repr at app/models/order.py line 18, not in the query itself. self.total is None for at least one of the returned orders (the total column is declared nullable=True), and the code calls .amount on it unconditionally. When FastAPI or logging tries to represent one of these Order objects as a string (for example when serializing the response or logging the result), __repr__ runs and crashes on the None value.

  2. Alternative hypotheses:

  • The total column itself is correctly populated but the Money type's .amount attribute name is wrong for this version of the library (less likely, since the error is specifically NoneType has no attribute, confirming total is None, not misnamed).
  • A specific order row was inserted without a total value due to a bug elsewhere (e.g., a failed payment webhook that created the order before charging it). Confirm by querying SELECT id FROM orders WHERE user_id = <id> AND total IS NULL;.
  1. Suggested fix:
def __repr__(self):
total_str = f"{self.total.amount}" if self.total is not None else "none"
return f"<Order {self.id} total={total_str}>"

Also consider whether orders should ever have a null total — if not, enforce it at the database level with nullable=False and backfill existing null rows.

  1. Verification step: Re-run the /orders/{user_id} endpoint for the same user_id that triggered the original error. Add a temporary log line before the query result is returned: logger.info([o.total for o in orders]) to confirm which order had a None total, then confirm the endpoint now returns a 200 response instead of raising AttributeError.

When to use it

  • A production error log or exception monitoring tool (Sentry, Datadog, CloudWatch) surfaced a stack trace and you need to triage it quickly
  • A CI pipeline failed with a traceback and you want to understand the failure before re-running the build blindly
  • You're debugging an intermittent or hard-to-reproduce error and need a second opinion on likely root causes from the trace alone
  • You inherited code you didn't write and the stack trace references functions or modules you're unfamiliar with

Best practices

  • Paste the full, unedited error message and stack trace in the original order the runtime produced it — don't paraphrase or summarize the exception text
  • Include the actual source code for every function or file named in the trace, not just the one where the error surfaced, since the root cause is often several frames up the call stack
  • State what you already tried or ruled out so the model doesn't waste the first response re-suggesting a fix you've already tested
  • Ask for multiple ranked hypotheses with the specific line or condition that would confirm each one, rather than a single fix, especially for intermittent or environment-dependent errors

Common mistakes

  • Pasting only the last line of the error message instead of the full stack trace, which hides exactly where the failure actually originated
  • Omitting the code for upstream functions in the call chain, so the model can only guess at what data or state triggered the exception
  • Not specifying the language version, framework version, or runtime environment, which matters for errors tied to deprecated APIs or breaking changes
  • Accepting the first suggested fix without asking the model to explain why that specific line causes that specific exception type

FAQs

Why does ChatGPT sometimes suggest a fix that doesn't match my actual error?

This usually happens when the stack trace is incomplete or the model wasn't given the code for every frame in the trace. ChatGPT will pattern-match the exception type to a common cause for that type even without full context, which produces a plausible but wrong guess. Always include the full trace and the code at each referenced line.

Should I paste the whole file or just the function that crashed?

Paste at minimum the function where the exception was raised plus every function listed in the stack trace above it, since the root cause is frequently several calls upstream from where the error actually surfaces. If a file is large, trim unrelated functions rather than truncating the relevant ones.

Does it matter which model I use for debugging a stack trace?

All major models (ChatGPT, Claude, Gemini) can parse structured stack traces well since they're trained on large amounts of code and error logs, but results depend far more on how complete the pasted context is than on which model you pick. Claude and GPT-4-class models tend to handle longer traces with more surrounding code without losing track of earlier details.

How do I debug an error that only happens intermittently and doesn't always produce the same trace?

Collect traces from several occurrences if possible and note what varies between them (input values, timing, concurrent requests), then ask the model to compare the traces for a common frame or condition rather than analyzing a single instance in isolation.

What Cuelara tool can help me build a stronger version of this prompt?

Prompt Optimizer — its Coding mode is built specifically to turn a messy debugging request and pasted trace into a structured prompt with clear constraints, which reduces the chance of the model jumping to an unverified fix.

Found this prompt useful? Share it.

Share

More in Code Generation & Software Engineering

Code Generation & Software Engineering

Claude Prompt to Refactor Legacy Code for Readability and Maintainability

This Claude prompt for refactoring legacy code is built for developers who've inherited a function or module that works but is hard to read,…

Role: You are a senior software engineer specializing in code readability and maintainability.

Context:
Language/framework: [LANGUAGE_AND_VERSION]
Style guide or conventions to follow: [STYLE_GUIDE_OR_LINTING_RULES]
What this code does: [BRIEF_DESCRIPTION_OF_FUNCTIONALITY]
Constraints (things that must not change): [PUBLIC_API_SIGNATURES_OR_OTHER_CONSTRAINTS]

Code to refactor:
[PASTE_FULL_FUNCTION_OR_FILE_HERE]

Instructions:
1. Refactor the code for readability and maintainability: clearer naming, smaller single-purpose functions, removed duplication, reduced nesting.
2. Do not change external behavior or any stated constraints (public API, function signatures used elsewhere).
3. List each change you made, one by one, with a short reason for it.
4. Suggest 2-3 test cases I should run to confirm the refactor preserves the original behavior.
5. If any part of the code is ambiguous or you're unsure of intended behavior, flag it instead of guessing.

Output format:
1. Refactored code in a fenced code block
2. A numbered list of changes with a one-line reason for each
3. Suggested test cases
Code Generation & Software Engineering

Prompt to Generate Unit Tests From a Function

This prompt turns an existing function into a set of unit tests covering its normal behavior, edge cases, and error handling, built for deve…

You are a senior software engineer writing unit tests.

Function to test:
[PASTE THE FUNCTION CODE]

Language and test framework: [E.G. TYPESCRIPT WITH VITEST, PYTHON WITH PYTEST]

Instructions:
1. Write tests covering normal, expected inputs.
2. Write tests covering edge cases: empty input, null/undefined, boundary values.
3. Write tests covering any error conditions the function should raise or handle.
4. Use clear, descriptive test names that state what is being verified.
5. Return only the test code, in a single code block, ready to run.

Output format: one fenced code block containing the complete test file.
Code Generation & Software Engineering

ChatGPT Prompt to Write Clear Commit Messages and Pull Request Descriptions

This ChatGPT prompt for writing commit messages and pull request descriptions turns a raw code diff into a clean, reviewable summary a teamm…

ROLE: You are a senior software engineer writing a commit message and pull request description for a code change.

CONTEXT:
- Code diff or summary of changes: [PASTE DIFF OR DESCRIBE THE CHANGE]
- Related ticket/issue: [TICKET ID AND TITLE, OR "NONE"]
- Commit convention to follow: [E.G. CONVENTIONAL COMMITS, FREEFORM, TICKET-PREFIXED]
- Audience for the PR description: [E.G. TEAM ENGINEERS, EXTERNAL CONTRIBUTORS]

TASK:
1. Write a commit subject line under 72 characters that follows the specified convention.
2. Write a 2-4 sentence commit body explaining what changed and, if context was given, why.
3. Write a pull request description with these sections: Summary, Why This Change Is Needed, How It Was Tested, Risk/Areas to Review Closely.
4. If the diff includes a schema change, new dependency, or breaking change, call it out explicitly under Risk/Areas to Review Closely.

CONSTRAINTS:
- Do not invent functionality, reasoning, or test coverage that wasn't stated or shown in the diff.
- Keep the PR description skimmable — short paragraphs or bullets, not dense prose.
- If information needed for a section is missing, write "Not specified" rather than guessing.

OUTPUT FORMAT:
Commit Subject: [text]
Commit Body: [text]

PR Description:
## Summary
[text]
## Why This Change Is Needed
[text]
## How It Was Tested
[text]
## Risk / Areas to Review Closely
[text]