023
LVL 01 — WAVE DEFENDER SESSION 023 DAY 23

ERROR HANDLING

🎫 PIXELCRAFT-011
🐛 Bug | 🔵 Easy | Priority: 🔴 Critical

If no image is loaded and you click any filter button, the page crashes with a white screen. No error message shown. Users think the app broke.

Steps to Reproduce: Open PixelCraft → Click "Grayscale" (without uploading an image) → white screen
Expected: Friendly message: "Please upload an image first"
Actual: White screen crash
CONCEPTS.UNLOCKED
🛡
Error Handling: try...catch...finally
try { risky code } catch (error) { handle it } finally { always runs }. The try block attempts something dangerous. If it throws, catch intercepts the error before it crashes the page.
Error Types
TypeError: wrong type ("null has no properties"). ReferenceError: variable doesn't exist. RangeError: value out of range. Each tells you what went wrong.
💥
Throwing Custom Errors
throw new Error('descriptive message') — create your own errors with clear messages. Don't let the system throw cryptic errors; throw meaningful ones first.
🔒
Defensive Programming
Validate inputs before processing. Check if the canvas context exists, if dimensions are valid, if the image is loaded. Catch problems early with clear messages.
💬
User-Friendly Error Messages
Users should NEVER see "TypeError: Cannot read properties of null." They should see "Please upload an image first." Toast notifications, NOT console errors.
🍞
Toast Notifications
Small popup messages that appear briefly and disappear automatically. Red for errors, yellow for warnings, green for success. The standard way to communicate state changes to users.
HANDS-ON.TASKS
01
Reproduce the Crash

Click Grayscale with no image loaded → console shows:

TypeError: Cannot read properties of null
This is the most common error in JavaScript. It means you tried to access a property on something that is null or undefined — the data doesn't exist yet.
02
Add Defensive Validation
function applyFilter(ctx, width, height, filterFn) { if (!ctx) throw new Error('Canvas context not initialized'); if (width <= 0 || height <= 0) throw new Error('Invalid canvas dimensions'); const imageData = ctx.getImageData(0, 0, width, height); // ... rest of function }
These checks run BEFORE the expensive pixel loop. If the canvas isn't ready, we fail immediately with a clear message — not halfway through processing millions of pixels.
03
Wrap Calls in try/catch
grayscaleBtn.addEventListener('click', () => { try { applyFilter(ctx, canvas.width, canvas.height, grayscale); } catch (error) { showToast(error.message, 'error'); } });

If applyFilter throws, the catch block catches the error and shows a toast instead of crashing the page.

04
Build a Toast Notification System
function showToast(message, type = 'info') { const toast = document.createElement('div'); toast.className = `toast toast-${type}`; toast.textContent = message; document.body.appendChild(toast); setTimeout(() => toast.remove(), 3000); }
document.createElement creates a new HTML element from JavaScript. appendChild adds it to the page. setTimeout removes it after 3 seconds. This is DOM manipulation in action.
05
Style the Toasts

CSS for the toast notifications:

ClassColorMeaning
.toast-errorRed backgroundSomething failed
.toast-warningYellow backgroundCaution, check this
.toast-successGreen backgroundAction completed
.toast-infoBlue backgroundNeutral information

Add position: fixed, bottom-right corner, slide-in animation from Session 17.

06
Add Error Handling to ALL Filters

Wrap every filter button's event listener in try/catch. Test each:

Test CaseExpected Toast
Empty canvas + any filter"Please upload an image first"
Corrupt image data"Failed to process image"
Extreme slider valuesShould work (clamping handles it)
07
Close the Ticket
git switch -c bugfix/PIXELCRAFT-011-error-handling git add src/scripts/ src/styles/ git commit -m "Add error handling and toast notifications (PIXELCRAFT-011)" git push origin bugfix/PIXELCRAFT-011-error-handling # PR → Review → Merge → Close ticket ✅
CS.DEEP-DIVE

Fail-safe vs fail-fast design philosophy.

Error handling strategy depends on context — a critical engineering decision.

// Two opposing philosophies:

Fail-safe  → nuclear plant shuts down
              safely on error
            → production app shows toast,
              never crashes

Fail-fast  → dev build crashes immediately
              so developers notice
            → unit tests fail loudly
              on any unexpected state

// PixelCraft in production must fail-safe:
// show an error toast, never crash.
// Every production system needs a clear
// error philosophy.
"Bulletproof App"
[A] Try to break PixelCraft in every way you can think of: double-click buttons rapidly, upload a 0-byte file, resize the window while applying a filter. Add error handling for each crash.
[B] Add a toast queue: if 3 toasts fire at once, stack them vertically instead of overlapping. Auto-dismiss from oldest to newest.
[C] Research how Gmail, Figma, or VS Code handle errors. When do they show toasts? When do they show dialogs? When do they silently log?
REF.MATERIAL
ARTICLE
Mozilla Developer Network
Complete guide to try/catch/finally, throw, Error types, and error handling best practices in JavaScript.
ERRORSMDNREFERENCE
VIDEO
Web Dev Simplified
Practical walkthrough of try/catch, custom errors, and real-world error handling patterns in JavaScript apps.
ERRORSPRACTICAL
ARTICLE
javascript.info
In-depth coverage of error handling: try/catch mechanics, the Error object, custom errors, and rethrowing. Interactive examples.
TRY/CATCHINTERACTIVE
VIDEO
Traversy Media
Build a full toast notification system with HTML, CSS, and JavaScript: animations, auto-dismiss, and stacking.
TOASTUIBUILD
ARTICLE
Wikipedia
The philosophy of writing code that anticipates failure: input validation, error boundaries, and graceful degradation.
DEFENSIVEPHILOSOPHY
// LEAVE EXCITED BECAUSE
PixelCraft never crashes anymore. Errors become friendly messages. This is the difference between amateur and professional software.