Ensiklopedia VibeKoding: Principles of Debugging.Ensiklopedia VibeKoding: Principles of Debugging.
The code is done, you run it, and it throws an error โ now what? Many beginners get stuck at this point, staring at the screen not knowing what to do. Debugging is one of the most core skills in programming โ arguably even more important than writing code itself. Writing code only accounts for about 30% of development time; the remaining 70% is spent understanding problems, locating bugs, and verifying fixes.The code is done, you run it, and it throws an error โ now what? Many beginners get stuck at this point, staring at the screen not knowing what to do. Debugging is one of the most core skills in programming โ arguably even more important than writing code itself. Writing code only accounts for about 30% of development time; the remaining 70% is spent understanding problems, locating bugs, and verifying fixes.
What will you learn in this article?What will you learn in this article?
After completing this chapter, you will gain:After completing this chapter, you will gain:
| Chapter | Content | Core Concepts |
|---|---|---|
| Chapter 1 | Reading Error Messages | Error types, stack traces |
| Chapter 2 | Classic Debugging Methods | Binary search, rubber duck, minimal reproduction |
| Chapter 3 | Debugging Toolbox | Breakpoints, logging, network capture |
| Chapter 4 | Debugging in the AI Era | AI assistance + human judgment |
| Chapter 5 | Debugging Mindset and Habits | Defensive programming, debug logs |
------
Debugging is not about "getting lucky" โ it's a rigorous scientific process. The methodology physicists use in experiments applies perfectly to debugging:Debugging is not about "getting lucky" โ it's a rigorous scientific process. The methodology physicists use in experiments applies perfectly to debugging:
- Reproduce first, then fix: If you can't reliably reproduce a bug, you won't know if your fix actually worked - Change only one variable at a time: If you change multiple things simultaneously, you won't know which change solved the problem - Trust evidence, not intuition: The place where you think "it can't possibly be the problem" is often exactly where the problem is - What changed recently?: 80% of bugs are introduced by recent changes- Reproduce first, then fix: If you can't reliably reproduce a bug, you won't know if your fix actually worked - Change only one variable at a time: If you change multiple things simultaneously, you won't know which change solved the problem - Trust evidence, not intuition: The place where you think "it can't possibly be the problem" is often exactly where the problem is - What changed recently?: 80% of bugs are introduced by recent changes
------
The most common beginner mistake: panicking when seeing an error, immediately closing or ignoring it. In reality, error messages are the program telling you what went wrong โ they are your best friends.The most common beginner mistake: panicking when seeing an error, immediately closing or ignoring it. In reality, error messages are the program telling you what went wrong โ they are your best friends.
| Type | When It Appears | Example | Difficulty |
|---|---|---|---|
| Syntax Error | Before the code even runs | Missing bracket, misspelled keyword | Easiest to fix |
| Runtime Error | Code crashes at a specific line | Accessing an undefined variable, division by zero | Medium difficulty |
| Logic Error | Code runs but produces wrong results | Wrong calculation formula, reversed conditional logic | Hardest to detect |
Using JavaScript as an example, here's a typical error message:Using JavaScript as an example, here's a typical error message:
CODE TypeError: Cannot read properties of undefined (reading 'name') at getUserName (app.js:15:23) at handleClick (app.js:42:10) at HTMLButtonElement.<anonymous> (app.js:58:5)
Read from top to bottom:Read from top to bottom:
TypeError, attempting to read the name property of undefinedFirst line: Error type + error description โ TypeError, attempting to read the name property of undefinedgetUserName function, app.js line 15, column 23Second line: The function and location where the error occurred โ getUserName function, app.js line 15, column 23handleClick โ button click eventSubsequent lines: The call chain โ Who called this function? handleClick โ button click eventRead top-down for the cause, bottom-up for the origin. The first line tells you "what went wrong," the last line tells you "where it started."Read top-down for the cause, bottom-up for the origin. The first line tells you "what went wrong," the last line tells you "where it started."
| Error Name | Meaning | Common Causes |
|---|---|---|
SyntaxError | Syntax error | Mismatched brackets, missing commas |
TypeError | Type error | Operating on undefined/null |
ReferenceError | Reference error | Using an undeclared variable |
RangeError | Range error | Array out of bounds, too deep recursion |
NetworkError | Network error | API request failed, CORS issues |
404 Not Found | Resource not found | Wrong URL, file deleted |
500 Internal Server Error | Server internal error | Backend code crash |
Python's stack trace is the opposite of JavaScript โ read from bottom to top:Python's stack trace is the opposite of JavaScript โ read from bottom to top:
python Traceback (most recent call last): File "main.py", line 10, in <module> result = calculate(data) File "main.py", line 5, in calculate return data["price"] * data["quantity"] KeyError: 'quantity'
The last line is the actual error cause: KeyError: 'quantity' โ the dictionary doesn't have the key quantity.The last line is the actual error cause: KeyError: 'quantity' โ the dictionary doesn't have the key quantity.
Regardless of the language, error messages contain three key pieces of information: what went wrong (error type), where it went wrong (file and line number), why it went wrong (error description). Learn to extract these three pieces of information, and you can read error messages in any language.Regardless of the language, error messages contain three key pieces of information: what went wrong (error type), where it went wrong (file and line number), why it went wrong (error description). Learn to extract these three pieces of information, and you can read error messages in any language.
------
These methods require no tools at all โ just your brain. They are the foundation of all advanced debugging techniques.These methods require no tools at all โ just your brain. They are the foundation of all advanced debugging techniques.
Core idea: Narrow the problem scope by half, then half again, until you find the root cause.Core idea: Narrow the problem scope by half, then half again, until you find the root cause.
Scenario: The code is long and you don't know which section has the problem.Scenario: The code is long and you don't know which section has the problem.
Steps:Steps:
console.log (or print) in the middle of the codeAdd a console.log (or print) in the middle of the codeCODE 100 lines of code with a bug โ Add log at line 50 Problem is in lines 50-100 โ Add log at line 75 Problem is in lines 50-75 โ Add log at line 62 Problem is in lines 60-62!
100 lines of code: at most 7 attempts (logโ100 โ 7) to locate the specific line. Even 1000 lines only need 10 attempts.100 lines of code: at most 7 attempts (logโ100 โ 7) to locate the specific line. Even 1000 lines only need 10 attempts.
Core idea: Explain the problem line by line to someone else (or a rubber duck). While explaining, you'll often discover the issue yourself.Core idea: Explain the problem line by line to someone else (or a rubber duck). While explaining, you'll often discover the issue yourself.
Why does it work? Because "writing code" and "explaining code" use different parts of your brain. When you're forced to verbally describe each step of the logic, assumptions you "thought were correct" get exposed.Why does it work? Because "writing code" and "explaining code" use different parts of your brain. When you're forced to verbally describe each step of the logic, assumptions you "thought were correct" get exposed.
How to practice:How to practice:
Core idea: Simplify a complex problem to the minimum โ keep only the code needed to trigger the bug.Core idea: Simplify a complex problem to the minimum โ keep only the code needed to trigger the bug.
Why it matters:Why it matters:
Steps:Steps:
Core idea: If the code "used to work and now it's broken," find which commit introduced the problem.Core idea: If the code "used to work and now it's broken," find which commit introduced the problem.
bash # Git's built-in binary search tool git bisect start git bisect bad # Mark the current version as having the bug git bisect good abc123 # Mark a known-good older version # Git automatically checks out the middle commit; you test and tell it good or bad # Repeat a few times to find the commit that introduced the bug
| Situation | Recommended Method | |-----|---------| | Don't know which section of code has the error | Binary search | | Logic looks correct but results are wrong | Rubber duck | | Bug in a complex system | Minimal reproduction | | "It was working fine and suddenly broke" | Regression / Git Bisect || Situation | Recommended Method | |-----|---------| | Don't know which section of code has the error | Binary search | | Logic looks correct but results are wrong | Rubber duck | | Bug in a complex system | Minimal reproduction | | "It was working fine and suddenly broke" | Regression / Git Bisect |
------
Methods are the foundation, but the right tools can multiply your debugging speed.Methods are the foundation, but the right tools can multiply your debugging speed.
Best for: Quickly checking variable values, confirming which code path was executed.Best for: Quickly checking variable values, confirming which code path was executed.
javascript // JavaScript console.log('Function called with params:', data) console.log('Calculation result:', result) console.table(arrayData) // Display arrays/objects in table format
python # Python print(f"Current value: {value}") print(f"Type: {type(data)}") # Check data types
Advanced techniques:Advanced techniques:
| Method | Purpose |
|---|---|
console.log() | Standard output |
console.warn() | Yellow warning โ easy to find in large logs |
console.error() | Red error |
console.table() | Display arrays and objects in table format |
console.time() / console.timeEnd() | Measure code execution time |
console.trace() | Print the call stack |
Best for: Complex logic that requires tracking the code execution process step by step.Best for: Complex logic that requires tracking the code execution process step by step.
In the browser (Chrome DevTools):In the browser (Chrome DevTools):
In VS Code:In VS Code:
console.log is great for quick verification โ use it and delete it. Breakpoint debugging is for deep analysis of complex logic. They complement each other rather than replace one another.console.log is great for quick verification โ use it and delete it. Breakpoint debugging is for deep analysis of complex logic. They complement each other rather than replace one another.
Best for: The page displays incorrectly, but you're not sure if it's a frontend problem or bad data from the backend.Best for: The page displays incorrectly, but you're not sure if it's a frontend problem or bad data from the backend.
Chrome DevTools โ Network Panel:Chrome DevTools โ Network Panel:
| What to Check | What Problems You Can Discover |
|---|---|
| Status Code | 404 (wrong URL), 500 (server crash), 403 (no permission) |
| Request Parameters | Is the data sent from the frontend correct? |
| Response Data | Is the data format returned by the backend correct? |
| Request Timing | Which API is too slow and dragging down the page |
| Request Headers | Is the Token included? Is Content-Type correct? |
Debugging mnemonic: Check the status code first, then request parameters, then response data.Debugging mnemonic: Check the status code first, then request parameters, then response data.
| Problem Type | Recommended Tool |
|---|---|
| Variable values are wrong | console.log / breakpoints |
| Logic execution order is wrong | Breakpoint debugging |
| API request failed | Network panel |
| Page styling is wrong | Elements panel (inspect CSS) |
| Performance issues | Performance panel / console.time |
| Memory leaks | Memory panel |
------
AI tools (ChatGPT, Claude, Cursor, etc.) can greatly accelerate debugging โ but only if you know how to use them properly.AI tools (ChatGPT, Claude, Cursor, etc.) can greatly accelerate debugging โ but only if you know how to use them properly.
| AI Is Good At | AI Is Not Good At |
|---|---|
| Explaining what error messages mean | Understanding your business logic |
| Providing solutions for common problems | Judging which solution fits your project best |
| Generating debugging code snippets | Reproducing bugs that only occur in specific environments |
| Analyzing potential issues in code | Understanding complex system context |
Bad question:Bad question:
> "My code has an error, can you help me look at it?"> "My code has an error, can you help me look at it?"
Good question:Good question:
> "I'm writing a form component in React, and when submitting I get TypeError: Cannot read properties of undefined (reading 'email'). Here's the relevant code: [paste code]. I've confirmed the API returns the correct data format, so the issue is likely in the frontend data processing."> "I'm writing a form component in React, and when submitting I get TypeError: Cannot read properties of undefined (reading 'email'). Here's the relevant code: [paste code]. I've confirmed the API returns the correct data format, so the issue is likely in the frontend data processing."
Question template:Question template:
CODE 1. What I'm doing: [context] 2. Expected behavior: [what should happen] 3. Actual behavior: [what actually happens] 4. Error message: [complete error] 5. Relevant code: [paste code] 6. What I've already tried: [what I ruled out]
1. AI may "confidently make things up": The solution AI provides might look reasonable but could be completely wrong. Always verify yourself. 2. AI doesn't know your context: It doesn't know your project structure, dependency versions, or runtime environment. You need to provide sufficient context. 3. Over-reliance on AI degrades your debugging skills: If you throw every error at AI, you'll never learn to debug on your own. Try analyzing the problem yourself for 5 minutes before asking AI.1. AI may "confidently make things up": The solution AI provides might look reasonable but could be completely wrong. Always verify yourself. 2. AI doesn't know your context: It doesn't know your project structure, dependency versions, or runtime environment. You need to provide sufficient context. 3. Over-reliance on AI degrades your debugging skills: If you throw every error at AI, you'll never learn to debug on your own. Try analyzing the problem yourself for 5 minutes before asking AI.
CODE Encounter a Bug โ Step 1: Read the error message yourself (1 minute) โ Step 2: Form your own hypothesis (2 minutes) โ Step 3: Quickly test the hypothesis (2 minutes) โ Still stuck? โ Send the error + code + your analysis to AI โ AI gives suggestions โ You judge if they're reasonable โ Verify
------
The best debugging is not needing to debug at all. Building good habits can reduce bugs at the source.The best debugging is not needing to debug at all. Building good habits can reduce bugs at the source.
Core idea: When writing code, assume "everything could go wrong" and build safeguards in advance.Core idea: When writing code, assume "everything could go wrong" and build safeguards in advance.
javascript // Bad: Assumes data definitely exists const name = data.user.name // Good: Defensive approach const name = data?.user?.name ?? 'Unknown User'
python # Bad: Assumes the file can always be opened content = open('config.json').read() # Good: Defensive approach try: content = open('config.json').read() except FileNotFoundError: print("Config file not found, using default configuration") content = '{}'
Logs are key to "post-mortem debugging." In production environments, you can't set breakpoints โ you can only rely on logs.Logs are key to "post-mortem debugging." In production environments, you can't set breakpoints โ you can only rely on logs.
| Log Level | Purpose | Example |
|---|---|---|
| DEBUG | Detailed info during development | Variable values, function parameters |
| INFO | Normal business flow | "User login successful", "Order created" |
| WARN | Non-blocking but noteworthy | "Cache miss", "Retry attempt 2" |
| ERROR | Something went wrong, needs handling | "Database connection failed", "API timeout" |
A good log entry should answer: when, where, what happened, and what the key data is. `` [2025-01-15 14:30:22] [ERROR] [OrderService] Failed to create order User ID: 12345, Product ID: 67890, Reason: Insufficient stock ``A good log entry should answer: when, where, what happened, and what the key data is. `` [2025-01-15 14:30:22] [ERROR] [OrderService] Failed to create order User ID: 12345, Product ID: 67890, Reason: Insufficient stock ``
When you encounter a bug, troubleshoot in this order:When you encounter a bug, troubleshoot in this order:
git diff to see recent changesWhat changed recently?: Use git diff to see recent changes| Trap | Correct Approach |
|---|---|
| Start modifying code without reading the error | Read the complete error message first |
| Change multiple things at once | Change one thing, verify, then change the next |
| Commit without testing after changes | Run tests after every modification |
| Only test on your own machine | Consider different environments (browsers, OS, network) |
| Don't clean up console.log after debugging | Delete all debug code before committing |
| Restart/reinstall whenever there's a problem | Understand the root cause first; restarting is only a temporary fix |
------
Debugging is a craft that requires deliberate practice. Let's review the core takeaways:Debugging is a craft that requires deliberate practice. Let's review the core takeaways:
Every bug is a learning opportunity. Each bug you fix builds your "pattern recognition" ability โ the next time you encounter a similar problem, you'll locate the cause faster.Every bug is a learning opportunity. Each bug you fix builds your "pattern recognition" ability โ the next time you encounter a similar problem, you'll locate the cause faster.
------