← JavaScript

Advanced · 4 of 11 · 18 min read

Errors and exception handling

Why try/catch misses asynchronous failures, what finally really guarantees, and how to build error types worth catching.

  • Error handling

try/catch catches what is thrown on the current stack, while the try block is running. Every confusing error-handling bug in JavaScript comes from that sentence being narrower than people expect.

The catch that never runs

try {
  setTimeout(() => {
    throw new Error('boom'); // runs in a later task, on an empty stack
  }, 0);
} catch (error) {
  console.log('never reached');
}
// The error escapes to the global handler instead.

The same with an unawaited promise:

async function fails() {
  throw new Error('nope');
}

try {
  fails();           // no await: this returns a rejected promise and moves on
} catch (error) {
  console.log('also never reached');
}

The fix is to put the handling where the failure actually happens:

// 1. await, so the rejection becomes a throw on *this* stack
async function run() {
  try {
    await fails();
  } catch (error) {
    console.log('caught:', error.message); // caught: nope
  }
}
run();

// 2. or .catch, for a promise you are not awaiting
fails().catch((error) => console.log('handled:', error.message));

// 3. inside the callback, for a timer or a listener
setTimeout(() => {
  try {
    throw new Error('boom');
  } catch (error) {
    console.log('caught in the callback');
  }
}, 0);
Failure Caught by a surrounding try/catch
a synchronous throw yes
JSON.parse on bad input yes
await somethingThatRejects() yes
a rejected promise with no await no
a setTimeout / setInterval callback no
an event listener no
a .then callback no — use .catch

Throw Error objects

Anything can be thrown. Only an Error carries a stack trace, a name and a type you can test:

try {
  throw 'something went wrong'; // legal, and unhelpful
} catch (error) {
  console.log(typeof error, error.stack, error instanceof Error); // "string" undefined false
}

try {
  throw new Error('something went wrong');
} catch (error) {
  console.log(error.name, error.message, typeof error.stack); // "Error" "..." "string"
}

Because a catch receives whatever was thrown, defensive code has to cope with both — which is exactly the cost of throwing strings:

function messageOf(thrown) {
  return thrown instanceof Error ? thrown.message : String(thrown);
}
console.log(messageOf(new Error('a')), messageOf('b')); // "a" "b"

The built-in types tell you what went wrong before you read the message:

Type Thrown when
TypeError a value is the wrong type — undefined.x, calling a non-function
ReferenceError a name does not exist, or is in the TDZ
SyntaxError the code or the JSON could not be parsed
RangeError a number or length is out of bounds; stack overflow
AggregateError several at once — Promise.any rejecting

Custom error types

Subclass Error so callers can branch on the type instead of matching strings:

class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = 'ValidationError'; // without this, logs say "Error"
    this.field = field;            // structured data beats parsing the message
  }
}

class NotFoundError extends Error {
  constructor(what, id) {
    super(`${what} ${id} was not found`);
    this.name = 'NotFoundError';
    this.status = 404;
  }
}

function handle(error) {
  if (error instanceof ValidationError) return `check ${error.field}`;
  if (error instanceof NotFoundError) return `404: ${error.message}`;
  throw error;                      // not ours — let it go up
}

console.log(handle(new ValidationError('email', 'is required'))); // "check email"
console.log(handle(new NotFoundError('order', 7)));               // "404: order 7 was not found"

Rethrowing what you do not recognise is the important line. A catch that swallows everything hides the bug you have not thought of yet.

Keeping the cause

Wrapping an error loses the original unless you say otherwise. cause is the standard way to keep it:

async function loadUser(id) {
  try {
    return await fetch(`/users/${id}`).then((r) => r.json());
  } catch (error) {
    throw new Error(`could not load user ${id}`, { cause: error });
  }
}

loadUser(1).catch((error) => {
  console.log(error.message);        // "could not load user 1"
  console.log(error.cause?.message); // the network error underneath
});

Your message says what the application was doing; the cause says what actually broke. Both are in the log.

finally

It runs whether the try succeeded, threw, or returned — which makes it the place for cleanup:

function read() {
  try {
    console.log('open');
    return 'data';
  } catch (error) {
    return 'failed';
  } finally {
    console.log('closed'); // runs before the function actually returns
  }
}

console.log(read()); // open / closed / data

It even runs when nothing catches:

function throws() {
  try {
    throw new Error('x');
  } finally {
    console.log('still cleaned up'); // runs, then the error continues upwards
  }
}
try { throws(); } catch { console.log('caught outside'); }
// "still cleaned up" then "caught outside"
function swallowed() {
  try {
    throw new Error('important');
  } finally {
    return 'everything is fine'; // the error vanishes
  }
}
console.log(swallowed()); // "everything is fine" — and nobody knows about the error

What finally does not guarantee: it will not run if the process exits, if the tab closes, or if an infinite loop never reaches it.

catch without a binding

When you do not need the error, omit the parameter entirely:

function isValidJSON(text) {
  try {
    JSON.parse(text);
    return true;
  } catch {
    return false; // ES2019: no `(error)` needed
  }
}
console.log(isValidJSON('{"a":1}'), isValidJSON('nope')); // true false

Fail fast

Validate at the boundary and throw immediately, rather than letting a bad value travel:

function transfer(from, to, amount) {
  if (!from || !to) throw new TypeError('both accounts are required');
  if (!Number.isFinite(amount)) throw new TypeError('amount must be a number');
  if (amount <= 0) throw new RangeError('amount must be positive');
  return { from, to, amount };   // past here, everything is known good
}

try {
  transfer('a', 'b', NaN);
} catch (error) {
  console.log(error.name, error.message); // TypeError amount must be a number
}

The alternative — returning null, or carrying on with NaN — produces a failure far from its cause, which is the expensive kind to debug.

The last line of defence

Handlers for what nothing else caught. They are for logging and a graceful message, not for business logic:

// Browser
// window.addEventListener('error', (e) => report(e.error));
// window.addEventListener('unhandledrejection', (e) => report(e.reason));

// Node
// process.on('uncaughtException', (error) => { report(error); process.exit(1); });
// process.on('unhandledRejection', (reason) => { report(reason); });

In Node an unhandled rejection terminates the process by default in current versions, which is the right behaviour: a process in an unknown state should not keep serving requests.

Common mistakes

Wrapping try around the scheduling instead of the work

Mistake. try { setTimeout(risky, 0) } catch {}. Why it fails. The try only covers the call to setTimeout, which never fails. The throw happens in a later task with an empty stack. What to do instead. Handle inside the callback, or await a promise so the rejection lands on your stack.

An empty catch

Mistake. catch {} to make a warning go away. Why it fails. The failure still happened; now it is invisible, and the next symptom appears somewhere unrelated. What to do instead. Handle it, log it, or rethrow. If a failure is genuinely expected and fine, say so in a comment.

catch for control flow

Mistake. Throwing to break out of a forEach, or using try/catch to test whether a key exists. Why it fails. Exceptions are for the exceptional; using them as a jump makes the normal path unreadable and slow. What to do instead. for...of with break, some, find, or Object.hasOwn for presence.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

A try/catch catches what is thrown synchronously inside it — and an async function does not throw.

Why does the catch never run?

Code sample
async function f() {
  throw new Error("boom");
}

try {
  f();
} catch (e) {
  console.log("caught");
}

console.log("done");

Why throw an Error object rather than a plain string?

What does a finally block guarantee?

Practise Error handling →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.