Error Handling & Debugging
Throw meaningful errors, handle only what you can recover from, and use browser tools to find the real cause.
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.
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.
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.
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.
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.
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.
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.
Explore a worked solution
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.
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.
Explore a worked solution
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.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
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.
[Process exited with code 0 - No output]
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.