Mastery Module 10 · Planning & Orchestration

When Things Break: Debugging with AI

What you'll learn

~25 min
  • Use the error sandwich format to describe any problem to AI
  • Read and interpret terminal errors and browser console errors
  • Follow a structured debugging workflow with AI as your partner
  • Know when to rollback and try a different approach
  • Apply prevention habits that reduce debugging time

You will learn to fix things when they break — using AI as your debugging partner instead of panicking. By the end of this lesson, you will have a repeatable system for turning any error into a solved problem, often faster and more systematically than you could on your own.

Why this matters

Things will break. Every project you build will produce errors — missing files, typos, failed installs, mysterious red text in the console. This is not a sign that something is wrong with you. This is software development.

The people who thrive are not the ones who never hit errors. They are the ones who fix errors fast. This is one of the most valuable employability skills in any technical role: when something breaks, you stay calm, gather information, and systematically fix it. AI makes this process dramatically faster — if you know how to talk to it about problems.

Mental model: the doctor visit

Think of debugging like visiting a doctor. You walk in and describe three things:

  1. What happened — “I was running on the treadmill and felt a sharp pain in my knee”
  2. The evidence — “It’s swollen and I can’t bend it past 90 degrees”
  3. What should be normal — “I should be able to bend my knee fully without pain”

The doctor uses all three pieces of information to diagnose the problem. If you walk in and just say “my body hurts,” the doctor has to play 20 questions before they can help.

AI debugging works the same way. The more structured your description, the faster the fix.

The error sandwich

This is the universal format for describing any problem to AI. It works for terminal errors, browser errors, deployment failures, broken layouts — everything.

What I did: [the action you took]
What happened: [the actual result, including the error message]
What I expected: [what should have happened]

Three lines. That is it. This format is usually enough to get a strong first diagnosis from the AI.

Worked example 1: terminal error

What I did: Ran npm run dev
What happened: Error: Cannot find module 'react'
What I expected: The dev server to start on localhost:3000

The AI immediately knows: you are missing the react dependency. It will tell you to run npm install and explain why.

Worked example 2: silent failure

What I did: Clicked the submit button on the contact form
What happened: Nothing happens — the page doesn't change, no error
in the console
What I expected: Form data to be sent and a success message to appear

The AI knows to look for a missing onSubmit handler, a preventDefault issue, or a broken API endpoint. Silent failures are the hardest bugs — the error sandwich forces you to describe exactly what “nothing” looks like.

Worked example 3: git error

What I did: Ran git push
What happened: error: failed to push some refs to
'https://github.com/user/repo.git'
What I expected: My code to be pushed to GitHub

The AI will likely explain that the remote has changes you do not have yet, and you need to git pull before you can push. Other possible causes include authentication issues, protected branch settings, or a misconfigured remote — the AI can help diagnose those too.

💡Copy-paste is your friend

You do not need to memorize error messages. Copy the full error output from your terminal, paste it into the “What happened” section, and let the AI read it. The details you think are noise are often exactly what the AI needs.

Before you paste

Strip API keys, passwords, tokens, and personal data from error output before pasting into any AI tool. If you are on a work or university machine, check your organization’s data-sharing policy first.

TRY ITYour dev server won't start. The terminal says 'ENOENT: no such file or directory, open package.json'. Write the first line of your error sandwich. Type it starting with 'What I did:'

Reading terminal errors

You covered the basics of terminal output in Reading AI Output. Here we go deeper into the errors themselves — what they mean, and the exact prompt to send to AI for each one.

The 5 most common terminal errors

1. “command not found”

Terminal window
bash: claude: command not found

What it means: The tool is not installed, or it is installed but your terminal does not know where to find it (not in PATH).

Prompt to AI:

What I did: Ran "claude" in my terminal
What happened: bash: claude: command not found
What I expected: Claude Code to start
I'm on [Mac/Windows WSL/Linux]. I installed it with [npm/pip/Homebrew/direct download].

2. “ENOENT: no such file or directory”

Error: ENOENT: no such file or directory, open '/home/user/project/config.json'

What it means: You are pointing to a file or folder that does not exist. Wrong path, wrong folder, or the file was never created.

Prompt to AI:

What I did: Ran npm run build
What happened: ENOENT: no such file or directory, open
'/home/user/project/config.json'
What I expected: The build to succeed
Here is my folder structure: [paste output of ls -la]

3. “EACCES: permission denied”

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

What it means: Your user account does not have permission to write to that location. Usually means you need to fix your Node installation (not use sudo).

Prompt to AI:

What I did: Ran npm install -g some-package
What happened: EACCES: permission denied
What I expected: The package to install globally
I installed Node via [nvm/direct download/apt]. I'm on [OS].

4. “Module not found” / “Cannot find module”

Error: Cannot find module 'express'

What it means: A dependency is missing. You either forgot to run npm install, or the package is not listed in your package.json.

Prompt to AI:

What I did: Ran npm run dev
What happened: Cannot find module 'express'
What I expected: The server to start
I just cloned this repo. Here is my package.json: [paste it]

5. “SyntaxError”

SyntaxError: Unexpected token '}' at line 42

What it means: There is a typo in the code — a missing comma, an extra bracket, an unclosed string. The error usually tells you the exact line number.

Prompt to AI:

What I did: Ran npm run dev
What happened: SyntaxError: Unexpected token '}' at line 42
What I expected: The app to start
Here is the file around line 42: [paste lines 38-46]
Always copy the FULL error message

Terminal errors often span multiple lines. The first line might say “Build failed” but the actual cause is buried 10 lines down. Copy everything from the first “Error” or “error” to the end of the message. More context is almost always better than too little — but scan for and remove any API keys, passwords, or personal information before pasting.

Reading browser errors

When your app runs but something is broken on the page, the clues are in the browser’s developer console. Open it with F12 (or Cmd+Option+J on Mac) and look at the Console tab.

Common console errors

“Uncaught TypeError: Cannot read properties of undefined”

Uncaught TypeError: Cannot read properties of undefined (reading 'map')

What it means: Your code tried to use something that does not exist yet. Often happens when data has not loaded or a variable is null.

“404 Not Found”

GET http://localhost:3000/api/users 404 (Not Found)

What it means: The page or API endpoint you requested does not exist. Check the URL for typos or make sure the route is set up.

“CORS error”

Access to fetch at 'https://api.example.com' from origin
'http://localhost:3000' has been blocked by CORS policy

What it means: The server you are trying to reach does not allow requests from your local development server. This is a server-side configuration issue.

The browser error prompt

Important: In the browser console, the full stack trace (file names and line numbers the AI needs) is often hidden behind a small triangle/arrow icon. Click it to expand the error before copying. Then use this template:

I'm seeing this error in my browser console:
[paste the full error]
The page is at localhost:3000/[page name].
The component that seems affected is [name or description].
What's causing this and how do I fix it?

The Network tab

Beyond the console, the Network tab in developer tools shows every request your page makes. Look for:

  • Red rows — these are failed requests
  • Status codes — 404 means “not found,” 500 means “server error,” 403 means “forbidden”
  • Click a failed request to see the response body, which often contains a detailed error message
💡Screenshot the error

If the error is visual (a broken layout, overlapping elements, missing content), take a screenshot and describe what you see. “The navigation bar is overlapping the hero section by about 20px” is more useful than “the layout is broken.”

The debugging workflow

Here is the complete step-by-step process for when something breaks. Follow these steps in order:

Step 1: Don’t panic

Errors are normal. Even experienced engineers see errors every day. An error message is not a failure — it is information.

Step 2: Copy the FULL error message

Select everything from the first “Error” to the end. Do not try to summarize it. Do not skip the “unimportant” parts.

Step 3: Write an error sandwich

What I did: [your action]
What happened: [paste the full error]
What I expected: [the correct behavior]

Step 4: Paste to AI

Send the error sandwich to your AI tool — whether that is Claude Code in the terminal, ChatGPT in the browser, or any other tool.

Redact sensitive information before pasting

Before pasting error messages or logs to any AI tool, scan for and remove: API keys, passwords, auth tokens, internal URLs, database connection strings, and any personally identifiable information (PII). Replace them with placeholders like [API_KEY] or [REDACTED]. AI tools process your input on remote servers — treat pasted content like a public post.

Step 5: Apply the fix

The AI will suggest a fix. Read it first (do you understand what it is changing?), then apply it.

Step 6: If the fix doesn’t work

Add to your conversation:

I tried [what the AI suggested] but I'm still getting [same or new error].
Here's the current error: [paste new error]

This gives the AI more information. Often the first fix reveals a deeper issue.

Step 7: The three-strike rule

If three AI suggestions have not fixed the problem, stop and rollback. Run:

Terminal window
git restore .

This reverts all modified files to their last committed state (see Saving Your Work for details on rollback). Note: git restore . does NOT remove new files the AI created. To also remove untracked files:

Terminal window
git clean -fd
git clean deletes files permanently

git clean -fd permanently deletes untracked files — they cannot be recovered. Run git clean -n first to preview what would be deleted. Only use this when you are sure you want to discard all new files.

💬This is not a you problem

When the AI hallucinates five times in a row, or the same error keeps coming back no matter what you try, it’s not because you’re bad at this. These tools have real limits — they lose context, they guess wrong, they confidently suggest fixes that make things worse. Every professional hits this wall. The skill isn’t avoiding failure. It’s knowing when to stop, reset, and try a different angle. Take a breath. You’re doing it right.

Then try a completely different approach. Tell the AI:

The previous approach didn't work after several attempts.
Let's try a different strategy. Here's what I'm trying to accomplish:
[describe the goal, not the failed approach]
💡Commit before risky fixes

Before applying a fix you are not sure about, run git add -A && git commit -m "checkpoint before fix attempt". It is okay to commit a broken state here — the goal is simply to save your current progress so the AI’s attempted fix does not make things worse. If you need to undo the fix attempt, use git restore . to discard uncommitted changes. If you need to undo the commit itself, use git revert HEAD to create a new commit that reverses the previous one (this is the safe option — it preserves history).

Prevention beats cure

The best debugging session is the one that never happens. Here are four habits that prevent most bugs:

1. Commit after every working state

Every time your project works — even partially — commit it. This gives you a safe rollback point.

Terminal window
git add -A && git commit -m "header component working"

2. Test after each change

Do not stack five changes and then test. Make one change, check if it works, then make the next change. When something breaks, you know exactly which change caused it.

3. Read the AI’s output before running commands

When the AI suggests a command or code change, read it first. Does it make sense? Is it modifying the right file? If you do not understand what it does, ask: “Explain what this command does before I run it.”

4. The “does it still work?” check

After every AI-generated change, switch to your browser (or run your test command) and verify the existing features still work. Catching a regression immediately is 10x easier than finding it after five more changes.

Context-specific debugging

🧬In Your Field: Biotechclick to expand

Debugging Python data pipelines. When a Python script fails, you will see a traceback — a stack of function calls showing where the error occurred. The most important line is the last one (the actual error) and the line number just above it. Your error sandwich: “What I did: Ran python analyze.py / What happened: [paste the full traceback] / What I expected: A CSV of results.” Also common in research: dependency conflicts. If pip install fails, include the full error and your Python version (python --version).

📊In Your Field: MIS / Businessclick to expand

Debugging dashboards and data tools. MIS projects often break at the data layer: a chart shows nothing, a table displays “undefined,” or a CSV upload silently fails. The key is checking the data before blaming the display. Add console.log(data) to your component (or ask the AI to add it) to see what the code is actually receiving. Common issues: date formats that don’t match, missing columns in uploaded CSVs, and API responses shaped differently than expected.

🏛️In Your Field: Government / State Devclick to expand

Debugging in restricted environments. Government and enterprise networks add extra debugging challenges: corporate proxies that block npm installs, firewalls that reject API calls, and VPN requirements for internal tools. When you see ETIMEDOUT, ECONNREFUSED, or SSL certificate errors, these are often network restrictions rather than code bugs — but also check that the service is running, the host/port is correct, and the endpoint is reachable. Your error sandwich should include: your network environment (on VPN? behind proxy?), the exact command, and the full error. The AI can suggest proxy configurations and alternative install methods.

Worked example: a full debugging session

Let us walk through a realistic debugging session from start to finish. Notice how each fix leads to the next issue — this is completely normal.

Start: You run npm run dev and get a build error.

Error 1 — missing import:

What I did: Ran npm run dev
What happened: Module not found: Can't resolve './components/Header'
What I expected: Dev server to start on localhost:3000

AI says: “The import ./components/Header does not match any file. Check the filename, path, and case sensitivity first.” You check — the file is actually called SiteHeader.jsx. You fix the import to ./components/SiteHeader. Run again.

Error 2 — typo in component:

What I did: Fixed the import to './components/SiteHeader', ran npm run dev again
What happened: SyntaxError: Unexpected token at SiteHeader.jsx line 14
What I expected: Dev server to start

AI says: “Line 14 has a missing closing parenthesis on the return statement.” You add it. Run again.

Error 3 — dev server starts but page is blank:

What I did: Fixed the syntax error, npm run dev now starts successfully
What happened: The page loads at localhost:3000 but it is completely blank,
no errors in terminal
What I expected: To see the homepage with the header and hero section

AI says: “Check your browser console for errors.” You open F12 and see:

Uncaught TypeError: Cannot read properties of undefined (reading 'title')

Error 4 — browser console error:

What I did: Checked the browser console after seeing a blank page
What happened: Uncaught TypeError: Cannot read properties of undefined
(reading 'title') at HeroSection.jsx line 8
What I expected: The hero section to render with the page title

AI says: “Your HeroSection component expects a data prop but it is not being passed. Add data={pageData} where you render <HeroSection /> in your main page file.” You make the fix. Refresh the browser.

Result: The page loads. Header is there. Hero section shows the title. Everything works.

Four errors. Four fixes. A few minutes. This is a completely normal development session. You do not need deep React expertise to start debugging effectively. You needed to know how to describe each problem clearly and apply the fix the AI suggested.

Practice: error sandwich format

Try reformatting these raw error situations into the three-line error sandwich format. The goal is to practice giving the AI structured information.

Scenario 1: You typed npm run dev and the terminal printed Error: listen EADDRINUSE: address already in use :::3000.

Example answer:

What I did: Ran npm run dev
What happened: Error: listen EADDRINUSE: address already in use :::3000
What I expected: The dev server to start on port 3000

Scenario 2: You uploaded a CSV file to your dashboard app, clicked “Generate Chart,” and nothing appeared. No error in the terminal, but the browser console shows TypeError: Cannot read properties of null (reading 'split').

Scenario 3: You ran git push origin main and got error: failed to push some refs to 'https://github.com/user/repo.git'.

Now try it yourself with a real or imagined error from your own projects. The more you practice, the more natural this format becomes.

Your web app shows a blank white screen after you added a new navigation component. Write an error sandwich to describe this problem to an AI debugging partner.

TRY ITWrite the 'What I did' line of an error sandwich for this scenario: You added a new navigation bar component to your React app and now the page is blank.
KNOWLEDGE CHECK

You ran 'npm install' and got 'EACCES: permission denied'. Which error sandwich gives the AI the best information?

KNOWLEDGE CHECK

You have tried three different AI-suggested fixes and the error is still there. What should you do next?

🔧

When Things Go Wrong

Use the Symptom → Evidence → Request pattern: describe what you see, paste the error, then ask for a fix.

Symptom
The AI's fix made things worse — now there are more errors than before
Evidence
I had one error, applied the AI's suggestion, and now I have three errors
What to ask the AI
"Rollback to your last working state with 'git restore .' to undo the bad fix. Then send the ORIGINAL error to the AI again with: 'The previous fix caused additional errors. Let's try a different approach. Original error: [paste it]. Goal: [what you're trying to accomplish].'"
Symptom
I can't find the error message
Evidence
The terminal scrolled past the error, or the app just doesn't work with no visible error
What to ask the AI
"For terminal: scroll up, or re-run the command and look for red or yellow text. For browser: open Developer Tools (F12) and check the Console tab. For silent failures: tell the AI 'No error message appears, but [describe what's not working]. The page/terminal shows [describe what you see].'"
Symptom
The error message is hundreds of lines long
Evidence
A giant wall of text appeared after running a command
What to ask the AI
"Find the FIRST error — it's usually near the top of the output, right after your command. Everything below it is often a chain reaction from that first error. Copy from the first 'Error' line through about 10 lines. If the AI needs more, it will ask."
Symptom
The AI says the fix should work but it doesn't on my machine
Evidence
I followed the AI's instructions exactly but get a different result
What to ask the AI
"Tell the AI your environment details: 'I'm on [Mac/Windows WSL/Linux], Node version [node --version], npm version [npm --version]. I followed your instructions but still see [error]. Could this be an OS or version difference?' Environment mismatches are one of the most common sources of 'works for me' bugs."
When to ask AI vs. when to search the web

Your AI tool is the best first stop for most errors — especially code-specific bugs, framework questions, and error message interpretation. But some situations are better handled by a web search:

  • Ask AI: Error messages, code bugs, “how do I do X in this framework,” explaining what code does, debugging specific behavior.
  • Search the web: Known outages or service status, version-specific changelogs, community discussions about whether a tool/library is worth using, official documentation for brand-new releases the AI may not know about.

When in doubt, try the AI first. If its answer seems outdated or generic, follow up with a targeted web search.

Key takeaways

  • The error sandwich works for every problem. “What I did / What happened / What I expected” — three lines that give the AI strong diagnostic context. Use this format every time.
  • Copy the full error message (but redact secrets first). The details you think are noise are often exactly what the AI needs to diagnose the problem.
  • Three-strike rule. If three AI suggestions do not fix the problem, stop. Rollback with git restore . and try a completely different approach.
  • Prevention beats cure. Commit after every working state, test after each change, and read the AI’s output before running it.
  • Errors are normal. Even expert engineers hit errors constantly. The skill is not avoiding errors — it is fixing them systematically.