> For the complete documentation index, see [llms.txt](https://personal-space-4.gitbook.io/complete-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://personal-space-4.gitbook.io/complete-guide/instructor_notes_gitbook/detailed-live-coding-script/step-3-error-handling.md). Agents can also search and read this documentation through its [MCP server](https://personal-space-4.gitbook.io/complete-guide/~gitbook/mcp).

# Step 3 — Error Handling

Error sebagai UI state + recovery.

{% hint style="danger" %}
**CONFIDENTIAL - DO NOT SHARE WITH STUDENTS**

This is the complete step-by-step guide with debugging checkpoints, theory references, and flow management.
{% endhint %}

***

## STEP 3: Error Handling (8 minutes)

{% hint style="info" %}
**Section Overview:** Implement error handling as UI state to provide better user experience.
{% endhint %}

#### \[PHASE 1: Theory - 2 minutes]

**THEORY REFERENCE:** `THEORY.md` - "Common Patterns" section (State Machine Pattern)

**Talking Points:**

#### Error as UI State (2 min)

**Show comparison:**

```javascript
// ❌ BAD: Error as side effect
function handleSend(text) {
  try {
    // ... code
  } catch (err) {
    console.error(err);  // Developer sees, user doesn't!
  }
}

// ✅ GOOD: Error as UI state
function handleSend(text) {
  try {
    // ... code
  } catch (err) {
    setError(err.message);  // User sees error in UI!
    setStatus('error');     // UI shows error state
  }
}
```

**Explain:**

{% hint style="info" %}
"Errors are part of user experience. Users need to know:

1. Something went wrong
2. What went wrong (error message)
3. What they can do (retry, change input, etc)

**Error handling pattern:**

* Catch error
* Set error state (message for user)
* Set status state ('error' for UI)
* Show error UI (red banner, icon, etc)
* Allow recovery (user can retry)

ChatShell already handles error UI. We just need to set state."
{% endhint %}

**Checklist Theory:**

* Students paham error = UI state
* Students paham error recovery pattern

***

#### \[PHASE 2: Live Coding - 4 minutes]

**Goal:** Add error trigger and handling

**Find handleSend, after validation, BEFORE creating userMessage:**

```javascript
function handleSend(text) {
  console.log("📤 SEND called with text:", text);
  
  if (!text.trim()) {
    console.log("⚠️ Empty text, ignoring");
    return;
  }
  
  console.log("✅ Text valid, proceeding...");
  
  // ADD ERROR HANDLING HERE:
  
  // Check for error trigger (demo purposes)
  if (text.toLowerCase().includes('error')) {
    console.log("🚨 Error trigger detected!");
    
    setStatus('error');
    console.log("🚦 Status set to error");
    
    setError('Simulasi error: kata "error" terdeteksi! Coba kata lain.');
    console.log("⚠️ Error message set");
    
    return;  // Stop execution, don't send message
  }
  
  // ... rest of handleSend
}
```

**Explain:**

{% hint style="info" %}
"**Error trigger for demo:** If user types word 'error', we simulate an error. Real app = API error, network error, validation error, etc.

**Error handling steps:**

1. Detect error condition
2. Set status to 'error'
3. Set error message (user-friendly!)
4. Return early (stop normal flow)

**UI response:** ChatShell will show red error banner with message."
{% endhint %}

***

**DEBUG TEST - Trigger Error:**

**Action:**

1. Save file
2. Clear console
3. Type "this is error" in chat
4. Send
5. Watch console and UI

**Expected console:**

```
📤 SEND called with text: "this is error"
✅ Text valid, proceeding...
🚨 Error trigger detected!
🚦 Status set to error
⚠️ Error message set
🔄 RENDER: Chat component rendered
🚦 Status state: error
⚠️ Error state: "Simulasi error: kata \"error\" terdeteksi! Coba kata lain."
```

**Expected UI:**

* Red error banner appears below messages
* Error message displayed
* No user message added

**Point out:**

{% hint style="success" %}
"Error state causes UI to show error banner. User sees clear feedback about what went wrong."
{% endhint %}

***

**DEBUG TEST - Error Recovery:**

**Action:**

1. After error shows, type normal message "hello"
2. Send
3. Watch error disappear

**Expected:**

* User message "hello" added
* Error banner disappears
* Bot responds normally

**Explain:**

{% hint style="success" %}
"Error recovery works automatically! Kenapa?

In handleSend, we have:

```javascript
setError(null);  // Clear any previous error
```

Every successful send clears old error. This is **error recovery pattern**."
{% endhint %}

***

#### \[PHASE 3: Verification - 2 minutes]

**Interactive Test with Students:**

**Test 1:** "Coba ketik 'error test' dan send"

* Should show error
* No message added

**Test 2:** "Sekarang ketik 'hello' dan send"

* Error disappears
* Message added
* Bot responds

**Test 3:** "Coba ketik 'my ERROR message'"

* Should trigger error (case-insensitive)

**Q\&A:**

**Q1:** "Kapan error state di-clear?"

**Expected answer:**

* Saat user send message baru
* Di handleClear
* Automatic recovery

**Q2:** "Bisa ada error dan loading bersamaan?"

**Expected answer:**

* No! Status machine - hanya satu state
* Either idle, loading, OR error

***

**Checklist Step 3 Complete:**

* Error handling implemented
* Error trigger works
* Error message shows in UI
* Error recovery works
* Students understand:
  * Error as UI state
  * State machine pattern
  * Error recovery pattern

**Time Check:** Should be around 38 minutes from workshop start

***
