Error Handling and Custom Errors

Intermediate · 9 min

`try`/`catch`/`finally`, subclassing `Error` for custom error types, and async failure modes: unhandled rejections and `await` slipping past `try`/`catch`.

Before thisPromisesAsync/Await

Bro Code · 9 min

Error Handling and Custom Errors

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Bro CodeReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `try` wraps code that might fail; `catch` runs only if something inside `try` throws; `finally` always runs afterward, whether or not anything was thrown — it's for cleanup that has to happen either way.
  • `throw` can raise any value, but throwing an `Error` (or a subclass of it) is the convention, because `Error` captures a `message` and a stack trace automatically — a thrown string gives you neither.
  • Subclassing `Error` (`class NotFoundError extends Error { ... }`) gives you your own error types: a `catch` block can check `error instanceof NotFoundError` and react differently per error type, instead of parsing an error message string to guess what went wrong.
  • `await`ing a rejected promise throws at that line like any other exception, which is exactly what lets a normal `try`/`catch` wrap `await`ed code — but only if you actually wrote the `try`/`catch` around it.
  • An async call whose promise is never `await`ed and never `.catch()`'d can fail silently as an "unhandled promise rejection" — its failure doesn't surface at the call site the way a synchronous `throw` would, because by the time it rejects, the surrounding synchronous code has already finished running.

The basics: try, catch, finally

try marks a block of code that might throw. If something inside it does, execution jumps straight to catch, skipping whatever was left in try. If nothing throws, catch is simply skipped. finally is the odd one out: it runs no matter what happened in the other two — success, caught failure, or even an uncaught one — which makes it the right place for cleanup that has to happen either way, like closing a file handle or hiding a loading spinner.

try {
  const config = JSON.parse(rawConfig);
  startApp(config);
} catch (error) {
  console.error("Couldn't start:", error.message);
} finally {
  hideLoadingSpinner();
}

throw can technically raise any value at all — a string, a number, a plain object — but the convention, almost without exception, is to throw an Error (or something built on it). new Error("message") captures a .message and a .stack trace automatically, at the exact moment it’s constructed. A thrown string gives you neither, which makes it much harder to trace a failure back to where it actually happened.

Your own error types: subclassing Error

A plain Error tells you that something failed and gives you a message. It doesn’t tell you what kind of failure it was, in a way code can act on. Subclassing Error fixes that:

class NotFoundError extends Error {
  constructor(resource) {
    super(`${resource} not found`);
    this.name = "NotFoundError";
    this.resource = resource;
  }
}

class ValidationError extends Error {
  constructor(field, reason) {
    super(`Invalid ${field}: ${reason}`);
    this.name = "ValidationError";
    this.field = field;
  }
}

Now a catch block can branch on type, not on parsing a message string:

try {
  const user = await getUser(id);
} catch (error) {
  if (error instanceof NotFoundError) {
    return respond404(error.resource);
  }
  if (error instanceof ValidationError) {
    return respond400(error.field);
  }
  throw error; // something unexpected — let it propagate
}

That last line matters: a catch block that doesn’t recognize an error type should generally re-throw it rather than swallow it silently. Handling only the failures you specifically know how to handle, and letting everything else continue to propagate, keeps a bug from getting hidden behind a generic “something went wrong” message.

Where async failure gets genuinely different

Everything so far works identically whether the code is synchronous or not — and that’s really the point of async/await: a rejected, awaited promise throws right at the await line, exactly like a synchronous throw, which is what makes an ordinary try/catch work around it at all:

try {
  const data = await fetchData();
  console.log(data);
} catch (error) {
  console.error("Fetch failed:", error.message);
}

The failure mode that’s genuinely new here is the unhandled promise rejection — and it comes directly from how the event loop actually runs this code. If you call an async function but never await it, and never attach a .catch() to what it returns, its promise is just left there:

function loadUser(id) {
  fetchUser(id); // not awaited, not returned, not .catch()'d
}

If fetchUser’s promise rejects, there is, by that point, no try/ catch still “around” it in any meaningful sense — the synchronous call to loadUser already finished and returned, same as a callback’s stack frame being long gone by the time it finally runs. The rejection has nowhere to go. Most environments will eventually report it as an “unhandled promise rejection” — in a browser, as a console warning; in Node, by default, as a process-level warning or even a crash — but it never reaches any catch block you wrote, because you never gave it one to reach. The fix is always the same: either await it inside a try/catch, or attach .catch() directly to the promise it returns.

Where this fits

This is the capstone of the asynchronous JavaScript group: it needs promises for what “rejected” even means, and async/await for why a rejected await behaves like a synchronous throw in the first place. Put together with the rest of this group, the full arc is: callbacks were the only option, promises gave failures a first-class shape, async/await made reading that code natural, and proper error handling is what makes all of it safe to run in production — catching what you can act on, and never leaving a rejection with nowhere to go.

Check yourself

  1. 01What's the difference in when `catch` and `finally` run, relative to the code in a `try` block?

    `catch` runs only if something inside `try` throws — if nothing throws, `catch` is skipped entirely. `finally` runs unconditionally, after `try` (and `catch`, if it ran) — whether the `try` block succeeded, threw and got caught, or threw and wasn't caught at all. That unconditional guarantee is why `finally` is the right place for cleanup, like closing a connection, that has to happen either way.

  2. 02Why is `throw new Error("message")` generally better than `throw "message"`?

    `new Error("message")` gives you an object with both a `.message` property and a `.stack` trace captured at the moment it was created, which is what makes debugging a thrown error practical. A plain thrown string has neither — you lose the stack trace entirely, and anything catching it has to assume it already knows what shape the thrown value is in.

  3. 03You write `class ValidationError extends Error {}` and throw it from a form-validation function. What does that buy you in the calling code's `catch` block that a generic `Error` wouldn't?

    The `catch` block can check `error instanceof ValidationError` and handle that specific failure differently from, say, a network error or a database error — showing a form message instead of a generic "something went wrong" screen, for instance. Without a custom error type, the only way to tell failures apart is inspecting the error's message text, which is fragile and not meant to be parsed.

  4. 04This code wraps an `await` in `try`/`catch`: `try { const data = await fetchData(); } catch (err) { console.error(err); }`. What makes this work, given that `fetchData` is asynchronous?

    A rejected promise, when `await`ed, throws its rejection as a regular synchronous-looking exception right at that `await` line — which is exactly what a `try`/`catch` is built to catch. It behaves as if the asynchronous failure happened as an ordinary `throw` at that exact point in the code, even though the actual work happened asynchronously.

  5. 05What's an "unhandled promise rejection," and how does forgetting `await` (or `.catch()`) cause one?

    It's a rejected promise that nothing ever checked — no `.catch()` was attached to it, and it was never `await`ed inside a `try`/`catch` either. If you call an async function without awaiting its promise (or without returning it to something that will), its eventual rejection has no handler waiting for it; by the time it actually rejects, the code that called it has already moved on, so the failure never surfaces at the call site the way a normal synchronous `throw` would.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark