Skip to main content
Albero Academy

Error Handling & Debugging

Catch and throw errors properly, create custom error types, handle async failures, and debug with the browser DevTools.

Chapter 11JavaScript15 min readBeginner friendly
  • #JavaScript
  • #Errors
  • #Debugging

Things go wrong — bad input, failed network calls, missing data. Robust code anticipates failure and handles it gracefully instead of crashing. This chapter covers try/catch, throwing your own errors, and — just as important — debugging with the browser's developer tools.

try / catch / finally

handling errors
try {
const data = JSON.parse(input); // may throw
process(data);
} catch (error) {
console.error("Bad input:", error.message);
} finally {
cleanup(); // always runs — success or failure
}

Throwing errors

Raise your own errors with throw when something is invalid. Throw an Error object (not a string) so you get a message and a stack trace:

throw
function enrol(age) {
if (age < 16) {
throw new Error("Must be at least 16 to enrol");
}
// …
}
try {
enrol(14);
} catch (e) {
console.log(e.message); // "Must be at least 16 to enrol"
}

Custom error types

Subclass Error to create meaningful error types you can catch specifically:

a custom error
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
try {
throw new ValidationError("email is required");
} catch (e) {
if (e instanceof ValidationError) {
// handle validation specifically
}
}

Async errors

With async/await, wrap awaits in try/catch. Remember (from Chapter 5) that fetch only rejects on network failure, so check response.ok yourself:

catching async failures
async function load() {
try {
const res = await fetch("/api/data");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (e) {
console.error("Load failed:", e.message);
return null; // graceful fallback
}
}

Debugging with DevTools

  • console.log for quick checks; console.table for arrays of objects; console.error/warn for severity.
  • Set breakpoints in the Sources panel to pause execution and inspect variables step by step.
  • Drop debugger; into your code to pause there when DevTools is open.
  • Read the stack trace bottom-to-top to find where an error originated.

Practice

Write a safeParse(json) that returns the parsed object or null on failure using try/catch. Create a ValidationError class and a function that throws it. Then set a breakpoint and step through a small buggy function in DevTools.

Key takeaways

  1. 01Wrap risky code in try/catch; finally always runs for cleanup.
  2. 02throw new Error(msg) for invalid states — throw Error objects, not strings.
  3. 03Subclass Error for custom types you can catch with instanceof.
  4. 04For async, try/catch around awaits and check response.ok — fetch doesn't reject on 404/500.
  5. 05Debug with console methods, breakpoints and debugger; read stack traces bottom-to-top.