Error handling and debugging
Handle errors with try/catch/finally, throw your own, deal with async failures, and debug calmly with DevTools.
In this lesson you will
- Recognise the error types
- Use try, catch and finally
- Throw and define your own errors
- Debug with console tools and breakpoints
About 21 minutes
Things go wrong. Plan for it.
The internet drops. A visitor types letters where numbers should go. A file you expected is missing. A server returns nonsense. None of these are bugs in your logic; they are facts of life. Professional code does not pretend errors will not happen. It expects them, handles them politely, and keeps the rest of the page working. This lesson teaches you how, and how to track down the errors that slip through.
The kinds of error
| Type | Cause | Example |
|---|---|---|
SyntaxError |
Broken grammar. Stops the file from running. | A missing bracket |
ReferenceError |
Using a name that does not exist | console.log(nmae) |
TypeError |
Using a value in the wrong way | null.length, calling a non-function |
RangeError |
A number outside the allowed range | new Array(-1) |
| Custom errors | Rules you define | “Password too short” |
try, catch, finally
try {
const data = JSON.parse("{ broken json");
console.log(data);
} catch (error) {
console.log("Could not read the data");
console.log(error.name + ": " + error.message);
} finally {
console.log("This always runs");
}
tryholds the code that might fail.catch (error)runs only if something insidetrythrows. Theerrorobject has aname, amessageand astack.finallyruns either way, perfect for cleaning up, such as hiding a loading spinner.
This code crashes. Wrap the risky line in try/catch so the program prints a friendly message and continues to the last line.
const text = '{ name: Sara }'; // invalid JSON
const user = JSON.parse(text);
console.log(user.name);
console.log('The program continues');
Put JSON.parse and the line using it inside try { }, and print a message in catch.
const text = '{ name: Sara }'; // invalid JSON
try {
const user = JSON.parse(text);
console.log(user.name);
} catch (error) {
console.log('Sorry, that data is not valid: ' + error.message);
}
console.log('The program continues');
Throwing your own errors
function withdraw(balance, amount) {
if (typeof amount !== "number" || Number.isNaN(amount)) {
throw new TypeError("Amount must be a number");
}
if (amount <= 0) throw new RangeError("Amount must be above zero");
if (amount > balance) throw new Error("Not enough money");
return balance - amount;
}
try {
console.log(withdraw(100, 150));
} catch (e) {
console.log(`${e.name}: ${e.message}`);
}
throw raises an error on purpose when a function receives something it cannot work with. Always throw an Error object (or one of its relatives), never a plain string, because error objects carry a helpful stack trace.
Custom error classes
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
try {
throw new ValidationError("email", "Enter a valid email");
} catch (e) {
if (e instanceof ValidationError) {
console.log(`Problem with ${e.field}: ${e.message}`);
} else {
throw e; // not ours: let it continue upward
}
}
Catching everything and hiding it is dangerous. The pattern above handles the errors you expect and re-throws the rest so they are not silently lost.
Errors in async code
async function loadData() {
try {
const res = await fetch("/api/data");
if (!res.ok) throw new Error("Server error " + res.status);
return await res.json();
} catch (error) {
console.error("Load failed:", error);
return []; // a safe fallback
}
}
// promises: .catch at the end of the chain
fetch("/api/data").then(r => r.json()).catch(err => console.error(err));
// last resort for anything nobody caught
window.addEventListener("error", e => console.log("Uncaught:", e.message));
window.addEventListener("unhandledrejection", e => console.log("Rejected:", e.reason));
A plain try/catch cannot catch an error thrown inside a setTimeout callback or in a promise you did not await. Put the try/catch inside the callback, or use await.
The async function fails. Use try/catch with await so that it prints ‘Failed: Network down’ instead of crashing, and use finally to print ‘Done’.
function risky() {
return new Promise((_, reject) => setTimeout(() => reject(new Error('Network down')), 300));
}
async function run() {
// await risky() safely
}
run();
try { await risky(); } catch (e) { console.log(‘Failed: ‘ + e.message); } finally { console.log(‘Done’); }
function risky() {
return new Promise((_, reject) => setTimeout(() => reject(new Error('Network down')), 300));
}
async function run() {
try {
await risky();
} catch (e) {
console.log('Failed: ' + e.message);
} finally {
console.log('Done');
}
}
run();
Debugging: finding the bug
Handling expected errors is one skill. Hunting the unexpected ones is another. Here is a calm, repeatable approach.
- Reproduce it. Find the exact steps that cause the problem every time.
- Read the message. The error names the type, the problem, the file and the line.
- Look at values.
console.logthe variables near the problem, or useconsole.table(array)for lists andconsole.dir(obj)for objects. - Use the debugger. Open DevTools → Sources, click a line number to set a breakpoint, and run the page. Execution pauses there and you can step line by line, hovering to see each variable.
- Shrink the problem. Remove code until the bug disappears; the last thing you removed is the culprit.
- Question assumptions. Is the element really found? Is that number really a number? Check, do not assume.
- Fix and test. Confirm the fix, then try the nearby cases.
console.log("value:", value);
console.table([{ a: 1 }, { a: 2 }]);
console.group("Step 1"); console.log("details"); console.groupEnd();
console.time("loop"); /* work */ console.timeEnd("loop");
console.assert(total >= 0, "Total should not be negative");
debugger; // pauses here when DevTools is open
Writing code that fails less
- Validate inputs at the start of a function.
- Return early for bad cases (guard clauses).
- Use optional chaining (
user?.address?.city) for data that may be missing. - Give defaults:
const name = input ?? "Guest". - Show friendly messages to visitors and keep technical details in the console or a log.
- Never ignore a catch. An empty
catch {}hides bugs for months.
Catching an error and doing nothing: catch (e) {}. The problem is still there, but now invisible. At minimum console.error(e), and ideally tell the visitor something helpful.
The first lines of an error’s stack show where it happened in your code. Lines from libraries come later. Click the file link in the console to jump straight to the line.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
When does the finally block run?
- Only on error
- Only on success
- Always, whether or not there was an error
- Never
finally runs either way.
Which keyword raises your own error?
throwraiseerrorfail
throw stops execution and jumps to a catch.
Which error type means “you used a name that does not exist”?
- TypeError
- ReferenceError
- RangeError
- SyntaxError
ReferenceError signals an undefined name.
How do you catch an error from await fetch()?
- You can’t
- Use finally only
- Use if/else
- Wrap it in try/catch
try/catch works with await.
What does a breakpoint do?
- Deletes a line
- Pauses the code so you can inspect it
- Skips an error
- Speeds up code
It lets you step through code and inspect values.
Summary
- try/catch/finally handle expected failures.
- throw new Error(…) signals problems clearly.
- Use try/catch with await for async code.
- Debug by reproducing, inspecting values and using breakpoints.
Questions
Should I wrap everything in try/catch?
No. Wrap risky operations (parsing, network, storage) and handle errors where you can do something useful about them.
What is the difference between console.log and console.error?
Both print. error is styled red and often captured by monitoring tools.
How do I find a bug that only happens on my visitor's phone?
Reproduce with device emulation or remote debugging, and log errors to a monitoring service.
