Error handling: try, catch and custom errors
Course contents (16 lessons)
- Modern syntax
- Destructuring, spread and rest
- ES modules: import and export
- Objects, this and errors
- Classes and prototypes
- Understanding this in JavaScript
- Error handling: try, catch and custom errors
- Asynchronous JavaScript
- The event loop: how JavaScript handles waiting
- From callbacks to promises to async/await
- Fetch and REST APIs
- Working in the browser
- Local storage and session storage
- Debugging with browser DevTools
- Performance basics: debounce and throttle
- Node.js essentials
- Node.js and npm basics
- Working with files in Node.js
- A tiny HTTP server with Node.js
- Testing and the final project
- Testing basics with the Node.js test runner
- Final project: a post explorer with modules and fetch
Things go wrong
Files are missing, the network fails, users type nonsense, and JSON arrives broken. A program that ignores this crashes at the worst moment. Good error handling means you decide what happens when something fails.
try, catch and finally
function parseSettings(text) {
try {
const settings = JSON.parse(text);
return settings;
} catch (error) {
console.log("Could not read settings:", error.message);
return {};
} finally {
console.log("Parsing finished");
}
}
console.log(parseSettings('{"theme":"dark"}'));
console.log(parseSettings("{ not valid json"));
Code inside try runs normally. If something throws, JavaScript jumps straight to catch, and the error variable holds what was thrown. The finally block runs in every case, whether there was an error or not. It is the place for cleanup, such as closing a file or hiding a loading spinner.
If you do not need the error object, you can write catch { ... } with no variable.
The Error object
Built-in errors have a name, a message and a stack:
try {
null.length;
} catch (error) {
console.log(error.name); // TypeError
console.log(error.message); // Cannot read properties of null...
console.log(error.stack); // where it happened
}
Common built-in types include TypeError (wrong type of value), ReferenceError (unknown variable), SyntaxError (bad syntax or bad JSON) and RangeError (number out of range).
Throwing your own errors
You can raise an error yourself with throw. Always throw an Error object and not a string, because only an Error carries a stack trace.
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
console.log(divide(10, 2)); // 5
console.log(divide(1, 0));
} catch (error) {
console.log("Error:", error.message);
}
The function does not know what to do about a bad input, but it knows the input is bad. So it throws, and the caller decides how to react. That is the core idea.
Custom error classes
For bigger programs, create your own types, so you can tell different problems apart.
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
function validateAge(age) {
if (!Number.isInteger(age)) {
throw new ValidationError("Age must be a whole number", "age");
}
if (age < 0 || age > 120) {
throw new ValidationError("Age is out of range", "age");
}
return age;
}
try {
validateAge(-5);
} catch (error) {
if (error instanceof ValidationError) {
console.log(`Problem with ${error.field}: ${error.message}`);
} else {
throw error; // not ours, pass it on
}
}
The instanceof check lets us handle validation problems and ignore the rest. The else { throw error } is important. It passes unexpected errors up instead of hiding them.
What to catch
Do not wrap everything in a try/catch and print "something went wrong". That hides real bugs. My rules:
- Catch errors you can do something useful about: show a message, use a default, retry.
- Let programming mistakes, such as a typo in a variable name, crash loudly during development. You want to see them.
- Catch near the place where you can make a decision, which is often not where the error happened.
- Never leave a
catchblock empty. At minimum, log the error.
Errors with a cause
When you catch an error and throw a new, clearer one, keep the original with the cause option:
function loadConfig(text) {
try {
return JSON.parse(text);
} catch (error) {
throw new Error("Config file is invalid", { cause: error });
}
}
Now the new error explains the high-level problem, and error.cause still has the technical detail.
Errors in async code
try/catch also works with await, which we cover in the async lessons:
async function getData() {
try {
const response = await fetch("/api/data");
return await response.json();
} catch (error) {
console.log("Request failed", error.message);
}
}
A plain try/catch cannot catch an error that is thrown inside a callback that runs later, such as the function you pass to setTimeout. The try block has finished by then. For callbacks and promises, the error must be handled inside the callback or in the promise chain.
Global handlers
As a last safety net, you can log errors that nobody caught. In a browser:
window.addEventListener("error", event => {
console.log("Uncaught:", event.message);
});
window.addEventListener("unhandledrejection", event => {
console.log("Unhandled promise rejection:", event.reason);
});
These are for reporting, not recovery. By the time they fire, the damage is done.
Common mistakes
- Throwing strings.
throw "oops"has no stack. Usenew Error("oops"). - Swallowing errors. An empty
catchmakes bugs invisible. - Catching too much code. Keep the
tryblock small. - **Forgetting that
JSON.parsethrows.** Always protect it when the text comes from outside. - **Expecting
tryto catch async errors from callbacks.** Handle them in the callback.
Try it yourself
- Write
safeParse(text, fallback)that returns the parsed JSON or the fallback when the text is invalid. - Create a
NotFoundErrorclass and a function that throws it when a key is missing from an object. - Add a
finallyblock that prints "done" and check that it runs even when the function returns insidetry. - Catch an error, wrap it in a new one with
cause, and printerror.cause.message.
function parseSettings(text) {
try {
const settings = JSON.parse(text);
return settings;
} catch (error) {
console.log("Could not read settings:", error.message);
return {};
} finally {
console.log("Parsing finished");
}
}
console.log(parseSettings('{"theme":"dark"}'));
console.log(parseSettings("{ not valid json"));
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account