Course outline · 0% complete

0/27 lessons0%

Course overview →

Error flows: catch and finally

lesson 5-3 · ~12 min · 13/27

Errors travel down the chain

A promise rejects when the executor calls reject(reason) or when a callback throws. From that point the rejection falls through the chain:

  • Every normal .then in between is skipped.
  • The first .catch (or .then with a second argument) receives the reason.
  • If the .catch returns normally, the chain is recovered and continues fulfilled from there.
  • .finally(fn) runs fn either way, for cleanup, and passes the result through untouched.

One .catch at the end of a chain covers every step above it. That is the promise version of wrapping everything in one try/catch.

This lesson matters beyond interviews: a failing network call is normal Tuesday traffic, not an exception, and an unhandled rejection can take down an entire Node process. Error paths are where junior code and production code differ the most.

Code exercise · javascript

Run it. The throw in step 1 skips step 2 entirely, lands in the catch, and the chain continues afterward because the catch returned a value.

catch can rethrow to translate errors

A .catch does not have to recover. If it throws, the chain becomes rejected again from that point. This is the standard way to translate errors: log the low-level reason, then hand a user-friendly error to the next layer. Everything between the rethrow and the next .catch is skipped, by the same falling-through rule as before.

Code exercise · javascript

Run it. The first catch logs the technical error and rethrows a friendlier one. The second catch is the one the UI layer would own.

Quiz

A rejection happens in step 1 of a five-step chain, and the only `.catch` is at the very end. What runs?

The unhandled rejection

If a rejection reaches the end of a chain with no .catch, the runtime reports an unhandled promise rejection. In modern Node this crashes the process. Interview take-away: every promise chain you start should end in a .catch (or be awaited inside try/catch, coming in lesson 6-1).

Code exercise · javascript

Your turn. `fetchUser` rejects for unknown ids. Add a `.catch` to the chain so a failure prints `fallback: guest` instead of crashing.