LESSON 30 · BEGINNER4 min read

Error Handling & Debugging

Throw meaningful errors, handle only what you can recover from, and use browser tools to find the real cause.

ES2024 / Node.js 20+Free to readModule 6 of 19
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Create and throw appropriate Error objects at validation boundaries.
  • Use try, catch, and finally with custom error classes and error.cause.
  • Separate developer diagnostics from user-facing messages.
  • Set breakpoints and read console output and stack traces effectively.

01Throw early with a useful error

An error is a value that represents a failed operation. throw stops normal execution and sends the value up the call stack until a catch handles it. Throw Error objects rather than strings so the value carries a name, message, and stack trace. Built-in subclasses add meaning: TypeError for a wrong kind of value, RangeError for a number outside an allowed range, and SyntaxError for malformed syntax.

Validate at the boundary where data enters your program, then trust it inside. A guard clause that throws early keeps the rest of a function free of defensive checks. Fail fast in development: a clear error at the source is easier to fix than a mysterious undefined several calls later. Do not use exceptions for ordinary branching, such as an optional field being empty.

quantity.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02Catch only what you can handle

try contains code that may fail, catch receives the error, and finally runs whether or not an error occurred. finally is the place for cleanup such as re-enabling a button or closing a connection. A catch block should handle the errors it understands and rethrow the rest. An empty catch hides bugs and makes failures appear as silent wrong behaviour.

Custom error classes make expected failures distinguishable. Extend Error, set this.name, and pass the original problem through the cause option. Then a caller can check instanceof ValidationError and show a form message, while an unexpected TypeError continues to the console. The cause chain preserves technical detail without confusing the user-facing message.

profile.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03Messages for two audiences

Every failure has two audiences. The developer needs the operation, input, and stack trace; the user needs a short explanation and a next step. Keep those messages separate. Log the technical detail, then render a stable sentence such as 'We could not save your changes. Try again.' Never insert an error message into the page with innerHTML, because it may contain text from an external system.

Preserve the user's work when an operation fails. Keep form values in place, mark the field that needs attention, and connect its message with aria-describedby. Use role='alert' for urgent errors and a polite status region for routine feedback. In production, report unexpected errors to a logging service; in development, let them surface loudly so they are fixed.

loading.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

04Debug with the browser

DevTools turns debugging into observation instead of guessing. Open the Sources panel, click a line number to set a breakpoint, then reload or trigger the code. Execution pauses before that line, and the Scope pane shows local and closure variables. Step over runs the current line; step into enters a called function; step out finishes it. A conditional breakpoint stops only when an expression is true.

The console complements breakpoints. console.table displays arrays of objects as columns, console.group and console.groupEnd organise related logs, and console.time with console.timeEnd measures a section. When an error appears, read the stack trace from the top: the top frame shows where it was thrown, and lower frames show the callers. Source maps map bundled code back to your original files.

debug-console.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

The ideas worth keeping.

  • Throw Error objects at boundaries with messages that name the failed expectation.
  • Catch only errors you can handle, use finally for cleanup, and preserve original failures with cause.
  • Use breakpoints and structured console output to find causes, and keep technical details out of user messages.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Wrap parsing in a custom error

Write a ConfigError class and a parseSettings(raw) function. Invalid JSON must throw ConfigError with the original error as cause. Parsed values that are null, arrays, or not objects must throw ConfigError with the message 'Settings must be an object'. Otherwise return the parsed object.

your_turn_1.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
class ConfigError extends Error {  constructor(message, options) {    super(message, options);    this.name = "ConfigError";  }}function parseSettings(raw) {  let value;  try {    value = JSON.parse(raw);  } catch (error) {    throw new ConfigError("Settings are not valid JSON", { cause: error });  }  if (!value || typeof value !== "object" || Array.isArray(value)) {    throw new ConfigError("Settings must be an object");  }  return value;}

The try block covers only the parse that can throw a syntax error. Shape validation happens after parsing, and both failure paths produce a named error the caller can identify.

02

Exercise 2: Trace a validation failure

Write assertPositive(value) that throws a TypeError with the message 'Expected a positive number' unless the value is a finite number greater than zero. Write total(values) that maps assertPositive over the array and sums the result. Call total([2, -1]) inside try/catch/finally, logging the error name and message in catch and 'Done' in finally.

your_turn_2.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
function assertPositive(value) {  if (!Number.isFinite(value) || value <= 0) {    throw new TypeError("Expected a positive number");  }  return value;}function total(values) {  return values.map(assertPositive).reduce((sum, value) => sum + value, 0);}try {  console.log(total([2, -1]));} catch (error) {  console.error(error.name + ": " + error.message);} finally {  console.log("Done");}

The error is thrown while mapping the second value, before reduce runs. The catch prints the error's type and message, and finally proves that cleanup code runs after failure.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01When does a finally block run?
02What is the purpose of the cause option on an Error?
03Which message is most appropriate to show a user?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

Exercise 1: Wrap parsing in a custom error

Write a ConfigError class and a parseSettings(raw) function. Invalid JSON must throw ConfigError with the original error as cause. Parsed values that are null, arrays, or not objects must throw ConfigError with the message 'Settings must be an object'. Otherwise return the parsed object.

EXPECTED OUTPUT
[Process exited with code 0 - No output]
main.jsJavaScript
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.