Bitpath

Lesson 1 · Unit 04

When a task fails

Errors, timeouts and cancellation in async code

13 exercisesabout 3 min

What you practise

  • Exceptions inside awaited tasks, one failure in a batch (gather vs return_exceptions, Promise.all vs allSettled), timeouts, cancelling work nobody is waiting for

Try a question from this lesson

Pick one

An async function fails instead of returning. What does this print?

import asyncio

async def load(user):
    if user == "bad":
        raise ValueError("no such user")
    return user

async def main():
    try:
        print(await load("bad"))
    except ValueError as err:
        print("caught:", err)

asyncio.run(main())
async function load(user) {
  if (user === "bad") {
    throw new Error("no such user");
  }
  return user;
}

async function main() {
  try {
    console.log(await load("bad"));
  } catch (err) {
    console.log("caught:", err.message);
  }
}
main();
async function load(user: string) {
  if (user === "bad") {
    throw new Error("no such user");
  }
  return user;
}
async function main() {
  try {
    console.log(await load("bad"));
  } catch (err) {
    const e = err as Error;
    console.log("caught:", e.message);
  }
}
main();

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Errors travel to the await

A failing async call does not blow up on the line that starts it. The error is stored inside the task or promise.

It is raised on the line that awaits the result.

So a try protects you only if the await is inside it. Start a call in one place and await it in another, and the error surfaces in the second place.

Concept

Never wait forever

A request can hang: the server is down, or the network has gone quiet. An await has no time limit of its own, so your code would wait for ever.

Put a timeout on every wait that leaves your process. When the limit passes, stop waiting and handle it like any other failure.

A slow answer that arrives after everyone has given up is worth nothing.

10 more exercises in the app

  • 4× multiple choice
  • 1× true or false
  • 1× fill the blanks
  • 3× type the answer
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy