QA Interview Hub · Knowledge base · Quizzes · Українська

TypeScript › Asynchrony: Promise, async/await, parallelism

Error handling in asynchronous code

In test code an error must reach the report with its true cause, so it is not swallowed but, when needed, rethrown with context and cause. An error in an async function becomes a rejected promise, and try/catch sees only the promises awaited inside it. The catch variable has type unknown and needs narrowing, and cleanup goes to a fixture, where the code after use() runs even after a failure.

TypeScript · Async

Creating the account «successfully» returned undefined. Where did the 500 error go?

The createAccount helper was wrapped in try/catch so it would «not fail over trifles». A week later tests fail in random places: «Cannot read properties of undefined (reading 'id')». The real cause, a 500 response from the API, was long ago swallowed in the helper. Error handling in test code has a different purpose than in a product: not to keep the system alive but to show the true cause of a failure as close as possible to where it happened.

How it works and why. An error in an async function becomes a rejected promise. await turns it back into an exception right at the place where it stands, so try/catch around await works as in synchronous code. But try/catch sees only the promises that are awaited inside it. A promise without await goes past:

async function run() {
  try {
    api.deleteAccount('acc-1');        // no await
  } catch {
    console.log('handled');            // never runs
  }
}

The rejection of such a promise becomes an unhandled rejection. An alternative to await with try/catch is .catch() on the promise itself: both ways are equivalent, but mixing them in one expression is not advisable.

Example: do not swallow, add context. The initial helper:

async function createAccount(): Promise<Account | undefined> {
  try {
    return await api.post('/accounts', { currency: 'UAH' });
  } catch {
    return undefined;   // a 500 and a timeout became "just no account"
  }
}

It turns a 500, a timeout and a network failure into the same undefined and the cause can no longer be recovered. Better to catch nothing, and if you do catch, rethrow with context. The cause option (ES2022) keeps the original error and the message says what exactly we were doing:

async function getBalance(accountId: string): Promise<number> {
  try {
    const res = await api.get('/accounts/' + accountId);
    return res.balance;
  } catch (err) {
    throw new Error('Failed to get balance for ' + accountId, { cause: err });
  }
}

The Playwright report shows the chain of causes, so such a message immediately shows both the step and the root source. For this lib must include ES2022 (with target: ES2022 it does).

What the person investigating a failure sees

Wrong

catch returns undefined

The failure comes on the next line: «Cannot read properties of undefined». The real cause, a 500 from the API, left no trace.

Right

Rethrow with cause

The report has the step («Failed to get balance for acc-1») and the root source (status and API response) in one chain.

Figure 1. An error must reach the report together with its cause instead of vanishing in a helper.

The error type in catch. Under strict (on by default since TypeScript 6.0) the variable in catch is unknown because anything can be thrown, not only an Error. Before touching fields it is narrowed:

try {
  await getBalance('acc-1');
} catch (err) {
  console.log(err.message);               // error: err is unknown
  if (err instanceof Error) {
    console.log(err.message, err.cause);  // ok, cause is unknown
  }
}

Negative tests. A manual try/catch in a test has a hole: if there is no error the catch branch does not run and the test passes. expect(promise).rejects fails in both cases:

// weak: if there is no error the test passes
try {
  await api.transfer({ amount: -100 });
} catch (e) {
  expect(String(e)).toMatch(/amount/i);
}

// reliable: no error fails the test as well
await expect(api.transfer({ amount: -100 })).rejects.toThrow(/amount/i);

Here it matters to pass the promise itself and not the result of a function that throws synchronously. If api.transfer is not declared async and throws before returning a promise, the error escapes before expect.

Playwright API tests and statuses.

const res = await request.post('/api/transfers', { data: { amount: -1 } });
expect(res.status()).toBe(400);          // a 4xx does not throw

const strict = await request.post('/api/transfers', {
  data: { amount: 10 },
  failOnStatusCode: true,                // throws on codes other than 2xx and 3xx
});
await expect(strict).toBeOK();

request.post() returns a response for any status by default, so the status is checked explicitly. The failOnStatusCode option makes it throw an error on codes other than 2xx and 3xx. Negative scenarios do not need it because a 4xx is expected there.

Limits and alternatives: finally and fixtures. finally guarantees cleanup, but in Playwright cleanup is better given to a fixture: the code after use() runs even when the test failed, and the test contains no try/finally of its own:

export const test = base.extend<{ account: Account }>({
  account: async ({ request }, use) => {
    const account = await createAccount(request);
    await use(account);
    await deleteAccount(request, account.id);   // runs even after the test failed
  },
});

An error in the cleanup itself must also be visible and not swallowed: otherwise garbage accumulates silently.

Common mistakes.

  • An empty catch or a catch with return undefined: a failure becomes a falsely green test or an unclear error further down.
  • A new error without cause: the original stack and the API response are lost.
  • Using err.message without narrowing: the compiler will not allow it under strict, and as Error only silences the problem.
  • A manual try/catch in a negative test without checking the success branch.
  • Expecting request.post() to throw on 4xx/5xx: by default it returns the response.

Check yourself

A test has try { await api.transfer({ amount: -100 }); } catch (e) { expect(String(e)).toMatch(/amount/) }. After a backend change transfer started returning 200. Will the test fail?

Answer

No. There is no error, the catch branch does not run, no check happens and the test is green. The bug (a negative amount accepted) slipped past. Use await expect(api.transfer(...)).rejects.toThrow(...): it fails also when there was no error.

Why pass { cause: err } to new Error(...) if the message already contains the account id?

Answer

The message says what we were doing and cause keeps why it failed: the original error with its stack, status or API response. Without it only our string remains and the root source has to be reproduced by hand.

In an interview. Junior: An error in async code is caught with try/catch around await. I do not swallow errors in helpers and I use expect(...).rejects in negative tests. Middle/Senior: In test code an error must reach the report with its true cause, so I rethrow with context and cause instead of returning undefined. The variable in catch is unknown and I narrow it. In Playwright request does not throw on 4xx/5xx, so I check the status explicitly, and I give cleanup to a fixture where code after use() runs even after the test failed.

More articles in this chapter