lecture 7 of 140 completed

Errors in asynchronous code

How a rejected promise and a failed assertion reach the test runner. A swallowed error makes a broken test pass.

What you'll learn

  • How try and catch work with await
  • How an error travels from a helper to the test runner
  • Why an empty catch block turns a failure into a pass

A Shelf test saves a reader's new email address and checks the confirmation. The save has been failing for a week. The test is green, and its log has one line that nobody reads: "save failed, continuing".

A rejected promise is how asynchronous code reports an error. With await, a rejected promise becomes a thrown error at the line of the await.

function saveEmail(email) {
  if (!email.includes("@")) {
    return Promise.reject(new Error("The email address is not valid"));
  }
  return Promise.resolve("saved " + email);
}

async function run() {
  try {
    const result = await saveEmail("ines.shelf.test");
    console.log(result);
  } catch (error) {
    console.log("caught: " + error.message);
  }
}

run();
caught: The email address is not valid
  1. try { ... } runs its block. If a line inside throws, the rest of the block is skipped.
  2. catch (error) { ... } runs only when something in the try block threw. error holds what was thrown.
  3. await saveEmail(...) waits for the promise. The promise is rejected, so the await throws the error, and console.log(result) never runs.

Promise.reject(...) creates a promise that is rejected from the start, the same way Promise.resolve(...) creates a fulfilled one.

How an error reaches the test runner

When nothing catches an error inside an async function, the function stops and the promise it returned is rejected. The caller that awaits that promise gets the same error thrown at its own await. The error travels up, one caller at a time.

function saveEmail(email) {
  return Promise.reject(new Error("The server answered 500"));
}

async function updateProfile() {
  await saveEmail("ines@shelf.test");
  console.log("profile updated");
}

async function test() {
  await updateProfile();
  console.log("checked the confirmation");
}

test()
  .then(() => console.log("runner: test passed"))
  .catch((error) => console.log("runner: test failed, " + error.message));
runner: test failed, The server answered 500

Neither "profile updated" nor "checked the confirmation" prints. The error skipped the rest of both functions and arrived at the last two lines, which stand in for the test runner.

A failed assertion works the same way. expect throws an error, or returns a rejected promise. Nothing in your test catches it, so it reaches the runner, and the runner marks the test as failed. That is the whole mechanism. A test fails because an error got all the way out.

This only works if every step is awaited. Without await on updateProfile(), the error has no caller to travel to. That is the missing await from the last lecture, seen from the other side.

The catch that hides a failure

Now the test from the top of the lecture.

function saveEmail(email) {
  return Promise.reject(new Error("The server answered 500"));
}

async function test() {
  try {
    await saveEmail("ines@shelf.test");
  } catch (error) {
    console.log("save failed, continuing");
  }
  console.log("checked the confirmation");
}

test()
  .then(() => console.log("runner: test passed"))
  .catch((error) => console.log("runner: test failed, " + error.message));
save failed, continuing
checked the confirmation
runner: test passed

The catch block received the error and did not pass it on. From the runner's side nothing went wrong. People add a block like this to get past a flaky step, and it stays in the code for years.

You have seen this shape before. The lecture on the missing await used .catch(() => {}) to keep an example quiet. It worked there for the same reason it is dangerous here: it makes a failure disappear.

In a test, an error you did not expect should end the test. There are two honest choices.

  • Remove the try and catch. The error reaches the runner by itself.
  • Keep them only to add information, and throw again: throw new Error("Saving the profile failed: " + error.message).

When catching is right

Catch an error when the error is what you are testing. Then say exactly which one you expect.

function saveEmail(email) {
  if (!email.includes("@")) {
    return Promise.reject(new Error("The email address is not valid"));
  }
  return Promise.resolve("saved " + email);
}

async function test() {
  let message = "no error";
  try {
    await saveEmail("ines.shelf.test");
  } catch (error) {
    message = error.message;
  }
  if (message !== "The email address is not valid") {
    throw new Error("Expected a validation error and got: " + message);
  }
  console.log("the bad address was refused");
}

test()
  .then(() => console.log("runner: test passed"))
  .catch((error) => console.log("runner: test failed, " + error.message));
the bad address was refused
runner: test passed

The check after the catch matters. Without it, the test would also pass when the save wrongly succeeds. Playwright's expect has a shorter form for this: await expect(promise).rejects.toThrow('not valid').

Remember this

With await, a rejected promise is thrown at that line. An error that nobody catches travels up through every awaiting caller to the test runner, and that is how a test fails. A catch that does not throw again hides the failure. Catch only the error you are testing for.

Reference: try...catch on MDN.

now prove it

Reading is the setup. Solve this exercise in the editor. We run your code on each case and compare what it prints with the expected output.