Your course progress0 of 14 chapters

Chapter 7

Finding and Fixing Bugs Automatically

Bugs aren't a sign you did something wrong. They're a normal part of every project, even for the most experienced developers in the world. The difference between a beginner and a pro isn't how many bugs there are, it's how fast they find and fix them.

This is where Claude Code really shines. It can read scary error messages, follow a problem across several files, find the source and fix it. Your job: give it the right clues, make sure it fixes the problem and doesn't just hide it, and know how to go back when something didn't work out.

Anatomy of an error message

An error message looks like gibberish, but it has a fixed structure. Here's a typical error from a Next.js project:

Sample error
TypeError: Cannot read properties of undefined (reading 'map')
    at RecipePage (app/recipes/[slug]/page.tsx:24:38)
    at renderWithHooks (node_modules/react-dom/cjs/react-dom-server.js:1523:18)
    at renderElement (node_modules/react-dom/cjs/react-dom-server.js:2104:9)
PartIn the exampleWhat it says
Error typeTypeErrorWhich category of problem. TypeError usually means "I tried to use something that isn't what I thought"
MessageCannot read properties of undefined (reading 'map')What happened: something tried to run map on something that doesn't exist (undefined)
Locationpage.tsx:24:38The file, line (24) and character (38) where it happened
Stack traceAll the at linesThe path the code took until it crashed, from closest to the problem to farthest

Step 1: Pass the error to Claude

A good bug report

Before pasting, take a moment to think like in chapter 4. Claude needs to know what you did, what you expected to happen, and what actually happened.

Weak prompt

It doesn't work, fix it

Strong prompt

When I open the page of a recipe I added through the form, the page crashes. I expected to see the recipe with its ingredients. Older recipes work normally. This started after we added the add-recipe form. Here's the error from the terminal: [paste the whole error]

The strong prompt gives five clues: where, what I expected, what happened, what does work, and since when. Each one narrows the search.

A template to copy:

What I did: [the action]. What I expected: [the desired result]. What actually happened: [what I saw]. What does work: [similar things that are fine]. Since when: [after which change]. The full error: [paste]

Four ways to pass an error

1. Copy and paste. The simplest: select the whole error in the terminal or browser, copy it and paste it to Claude. An error of a few lines goes through in one paste.

2. Run the command inside Claude Code, with !. Instead of running it in another window and copying, run it right in the conversation. The output, including errors, goes into the conversation, and Claude sees it all:

Inside Claude Code
! npm run build

And once the output appears, just write:

The build failed. Explain what the error means and find the cause

3. Pipe output straight from the terminal. If you haven't entered Claude Code yet, you can pipe a command's output to it. 2>&1 makes sure errors go through too, not just the regular output:

Windows PowerShell
npm run build 2>&1 | claude -p "Explain in plain English why the build failed and what needs fixing"

4. A screenshot. An error that appears in the browser, like Next.js's red error overlay or a page that looks broken, you can simply screenshot and paste: Ctrl + V, and on Windows Alt + V.

Step 2: Find the root cause

Symptom vs. cause

When you have a fever, you can take a painkiller and the fever goes down. But if there's an infection, it's still there. Code is the same: the place where the error shows up isn't always the place where the problem is.

In our example, the error shows up in page.tsx, on the line that displays the ingredients:

app/recipes/[slug]/page.tsx
<ul>
  {recipe.ingredients.map((item) => (
    <li key={item.name}>{item.amount} {item.unit} {item.name}</li>
  ))}
</ul>

This code is perfectly fine. The problem is in a different file: the add-recipe form saves the ingredients under a different name:

app/add/actions.ts
const newRecipe = {
  title: formData.get("title"),
  slug: makeSlug(formData.get("title")),
  ingredientsList: parseIngredients(formData.get("ingredients")), // ← name doesn't match
  steps: parseSteps(formData.get("steps")),
};

Recipes from the form are saved with ingredientsList, and the recipe page looks for ingredients. For it, the field simply doesn't exist, meaning undefined, and that's where the crash comes from.

Notice: to find this you have to follow the data through several files: the form, the save file, the JSON file and the recipe page. That's exactly what Claude does well, if you ask it to.

Ask for an investigation, not a fix

Weak prompt

Fix the error in page.tsx

Strong prompt

The recipe page crashes, only for recipes added through the form. Don't fix anything yet. Follow the data of such a recipe from the moment the form is submitted, through saving, until the page displays it. Tell me exactly where the data changes or gets lost, and what the root cause is.

The weak prompt points Claude to where the error shows up, and it might “fix” it there, for example with a check that hides the problem. The strong prompt sends it to look for the source, and separates investigating from fixing.

More investigation techniques

Ranked hypotheses. When the problem isn't clear, ask Claude to think like a detective:

Suggest three possible causes for the problem, from most to least likely. For each: how we'll check whether it's right, without changing code

What changed? If something worked yesterday and doesn't today, the answer is almost always in the latest changes. This is where Git (chapter 8) pays off:

This page worked in yesterday's commit and has been broken since. Compare the current code to the latest git commits, and tell me which change most likely caused the problem

Temporary logging. Sometimes you need to see what happens at runtime:

Add temporary logging (console.log) at the key points along the data's path, so we can see where it changes. Mark each log with a TEMP-DEBUG comment, so it's easy to remove them all once we've found the problem

Investigating a big project. If you need to search many files, you can ask Claude to use subagents. They read the files in a separate context window and return only the conclusions, so the main conversation doesn't fill up:

Use subagents to investigate every place in the project where recipes are saved or read, and give me a list of all the field names used in each place

Step 3: Fix and verify

A real fix vs. a cover-up

Once you understand the root cause, ask for a fix, and make sure it addresses the cause:

Now fix the root cause: unify the field name so the form saves ingredients, like all the other recipes. Also fix recipes already saved under the old name in the JSON file. In addition, add a friendly message to the recipe page if a recipe has no ingredients at all, instead of crashing

app/add/actions.ts: the fix
-  ingredientsList: parseIngredients(formData.get("ingredients")),
+  ingredients: parseIngredients(formData.get("ingredients")),

The simplest approach is to write this into the request up front:

Weak prompt

Make the error go away

Strong prompt

Fix the root cause. Don't hide the error with try/catch, ts-ignore or checks that skip the case. If you think there's no choice but to work around it, stop and explain why.

“Go away” is a goal you can reach with a cover-up too. “Root cause” plus the list of what's off-limits makes clear what counts as a real fix.

Reproduce first, then fix

The safest way to know a bug is fixed: see it happen, fix it, and see that it no longer happens.

Before you fix it, write a small test that reproduces the bug and fails. Then fix it, and run the test again to show it passes. Show me the output of both runs

If the project doesn't have automated tests yet, you can ask for a simpler version:

Write me a list of exact steps to reproduce the bug in the browser. I'll confirm it happens, and after the fix I'll check again using the same steps

The rule of two

If Claude has tried to fix something twice and still hasn't succeeded, don't keep asking "try again". The conversation is already full of failed attempts, and they confuse it. Instead:

  1. Go back to before the failed attempts (next section).
  2. Run /clear.
  3. Write a new request that includes what you learned: "We already tried X and Y and it didn't work, because Z".

Step 4: When the fix did harm, go back

Sometimes a "fix" breaks something else, or Claude changed more than you asked. No problem: there are several ways to go back, each suited to a different situation.

Instant stop: Esc

See Claude heading the wrong way? One Esc stops it immediately. The conversation is kept, and you can explain what to do differently.

Back in time: /rewind

Claude Code saves a checkpoint before every message you send, including a copy of the files it's about to change. To go back:

Inside Claude Code
/rewind

Or press Esc twice. A menu of your previous messages opens. Choose the point you want to go back to, and then choose what to restore:

OptionWhat happensWhen to use it
Code and conversationBoth the files and the conversation go back to the point you choseThe "fix" was a total mistake, and you want to start again from that point
Code onlyThe files go back, the conversation staysYou want to undo the changes, but have Claude remember what it tried and why it didn't work
Conversation onlyThe conversation goes back, the files stayThe code is fine, but the conversation got tangled and you need to restart it
Summarize from hereMessages from this point on are summarizedThe conversation is long, and you want to free up space without losing what happened

Going back with Git

Git is the strongest safety net, because it saves the whole state of the project no matter who changed it. If you saved a safe point before you started fixing (chapter 8), you can always go back to it.

Undoing unsaved changes in a specific file:

Show me what changed in app/page.tsx since the last git commit. If it's only the failed fix, restore just this file to the state of the last commit

What Claude will run (example)
git diff app/page.tsx
git restore app/page.tsx

Undoing a commit that was already made:

The last git commit broke the search. Undo it with git revert, so a new commit is created that reverses it, without deleting history

What Claude will run (example)
git log --oneline -3
git revert a3f9c21

git revert doesn't delete the problematic commit. It adds a new commit that reverses it, so it's safe even after the code is already on GitHub.

Which tool when?

SituationTool
Claude is mid-task and heading the wrong wayEsc
Claude edited files in this conversation, and the edit did harm/rewind (or Esc twice)
The change includes terminal commands, or you made changes yourselfGit: git restore for a specific file, after checking the diff
The change is already committed to gitgit revert
The change is already on GitHubgit revert, then a normal push. Never force push (chapter 8)

Step 5: Edge cases, the bugs that haven't happened yet

An edge case is an unusual situation the code isn't always ready for: an empty field, the number zero, very long text, a slow connection. Most bugs real users find are exactly these. The best way to deal with them: find them before your users do.

TypeExample on the recipe siteWhat might happen
EmptyA search containing only spacesAll recipes disappear, or none do
Zero or negativeA servings calculator set to 0Division by zero, NaN quantities
MissingA recipe with no emoji or no stepsA hole in the layout, or a crash
Very longAn 80-character recipe nameThe text overflows the card
Special charactersA name with quotes or an apostrophe: "Mom's 'Famous' Pie"Breaks a link or the search
Mixed languagesA recipe name mixing English and another scriptWords appear in the wrong order
Storage unavailableBrowsing in a private windowFavorites or step tracking crash

Weak prompt

Check that there are no bugs

Strong prompt

Go over the servings calculator feature and think about edge cases: empty values, zero, very large numbers, fractional quantities, and ingredients with no quantity (like “salt to taste”). For each case tell me what happens today, and if it's a problem, suggest a fix. Don't fix anything yet.

“No bugs” is a claim you can't check. A defined list of cases to check, with “what happens today” for each, is a real test.

Step 6: Fixing build errors (npm run build)

Why does it work in dev and break in build?

npm run dev is forgiving: it runs the site even with small problems, so you can keep working. npm run build prepares the version that goes live, and it's strict: it checks every file, TypeScript's types, and sometimes runs a code checker (lint) too. So it's not unusual for a site to work great in dev and fail in build.

The rule: run npm run build often, not just right before deploying. That way every problem stays small and easy to fix.

The common errors

Type error: the code passes a value of one type to a place that expects another type.

Sample output
./components/ServingsCalculator.tsx:14:7
Type error: Type 'string' is not assignable to type 'number'.
 
  12 |   const [servings, setServings] = useState(recipe.servings);
  13 |   function onChange(e) {
> 14 |     setServings(e.target.value);
     |                 ^

Here the value from the input box is text ("4"), and the code expects a number (4).

Module not found: a file or package the code tries to import doesn't exist, usually because of a wrong name, an uppercase or lowercase letter, or a package that wasn't installed.

Sample output
Module not found: Can't resolve '@/components/recipeCard'

(Notice: the file is called RecipeCard, with a capital R. On Windows this sometimes works in dev, and only breaks in the build or on the server.)

A client component without the directive: code that uses browser capabilities, like useState or clicks, without marking the file as a Client Component:

Sample output
You're importing a component that needs `useState`. This React Hook only works
in a Client Component. To fix, mark the file (or its parent) with the
`"use client"` directive.

Prerender error: the build tries to generate a page ahead of time, and something in it crashes. It's usually a data problem, like the ingredients example we saw.

Sample output
Error occurred prerendering page "/recipes/grandma-cheesecake".
TypeError: Cannot read properties of undefined (reading 'map')

The loop: build, fix, repeat

Run npm run build. If there are errors, fix the root cause of each one, and run it again. Repeat until the build passes without errors. You may not disable checks to get it to pass: no ts-ignore, no eslint-disable, and no config changes that ignore errors. At the end show me the final output, and summarize each fix you made in one sentence

Exercise: bug hunt

In this exercise Claude plants bugs, and you find them with its help, but in a different conversation, without knowing what it did. Work on the recipe site from chapter 6, or any project with Git.

Part A: Planting

  1. Make sure all your work is committed to git and the build passes.
  2. Ask Claude:

Create a new branch called bug-hunt. In this branch, deliberately introduce three different bugs: one that crashes a specific page, one that produces a wrong result with no error at all, and one that only shows up in an edge case. Don't tell me what you did or where. Write a description of the bugs to a file called BUGS-ANSWERS.md and commit everything to git

  1. Don't open BUGS-ANSWERS.md! Run /clear, so Claude "forgets" what it did.

Part B: Hunting

  1. Run npm run build and npm run dev, and try the site like a user. Found something odd?
  2. For each bug: a good bug report, an investigation in plan mode without fixing, and only then a fix of the root cause.
  3. Did the fix for one of the bugs do harm? Practice /rewind.
  4. Ask Claude to look for edge cases in the feature where you suspect the third bug is hiding.

Part C: Checking

  1. Only now open BUGS-ANSWERS.md and compare.
  2. Ask Claude to switch back to main and delete the bug-hunt branch. The original site wasn't affected, because everything happened in a separate branch.

Finished the exercise?

0 of 8

Summary

  • Pass the whole error: copy-paste, ! inside Claude Code, 2>&1 | claude -p, or a screenshot. With a bug report: what I did, what I expected, what happened, since when.
  • Investigate first, fix later: plan mode, following the data through every file, hypotheses, and checking what changed in git.
  • A real fix, not a cover-up: no swallowing try/catch, no ts-ignore and no turning off checks. Reproduce the bug, fix it, and verify.
  • Going back: Esc to stop, /rewind for Claude's edits, git restore and git revert for everything else.
  • Edge cases: empty, zero, missing, long, special characters. Find them before your users do.
  • Build errors: run npm run build often, and fix in a loop until it passes.

In the next chapter we'll get to know Git and GitHub in depth: branches, pull requests, code review and safety belts that protect your code.

Check yourself

1. Claude 'fixed' a bug with a try/catch that swallows the error. What's the problem?

2. What can't /rewind undo?

Answering every quiz question marks the chapter as done automatically.