Tutorials / Modern JavaScript: Async, Modules and the Browser / Error handling: try, catch and custom errors

Error handling: try, catch and custom errors

14 min read javascript
Course contents (16 lessons)
  1. Modern syntax
  2. Destructuring, spread and rest
  3. ES modules: import and export
  4. Objects, this and errors
  5. Classes and prototypes
  6. Understanding this in JavaScript
  7. Error handling: try, catch and custom errors
  8. Asynchronous JavaScript
  9. The event loop: how JavaScript handles waiting
  10. From callbacks to promises to async/await
  11. Fetch and REST APIs
  12. Working in the browser
  13. Local storage and session storage
  14. Debugging with browser DevTools
  15. Performance basics: debounce and throttle
  16. Node.js essentials
  17. Node.js and npm basics
  18. Working with files in Node.js
  19. A tiny HTTP server with Node.js
  20. Testing and the final project
  21. Testing basics with the Node.js test runner
  22. 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 catch block 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. Use new Error("oops").
  • Swallowing errors. An empty catch makes bugs invisible.
  • Catching too much code. Keep the try block small.
  • **Forgetting that JSON.parse throws.** Always protect it when the text comes from outside.
  • **Expecting try to catch async errors from callbacks.** Handle them in the callback.

Try it yourself

  1. Write safeParse(text, fallback) that returns the parsed JSON or the fallback when the text is invalid.
  2. Create a NotFoundError class and a function that throws it when a key is missing from an object.
  3. Add a finally block that prints "done" and check that it runs even when the function returns inside try.
  4. Catch an error, wrap it in a new one with cause, and print error.cause.message.
javascript
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