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

Logs and observability › Logs in automation

Browser console and page errors in Playwright

Browser errors in Playwright are caught with page.on events: console, pageerror, requestfailed and response. An event is delivered only to an already subscribed handler, so the subscription is made before the first goto, best as an auto-fixture that checks the error array after the test. The allowlist is kept narrow. For a popup the subscription is made at the context level.

Logs · Test automation

The e2e test is green while the browser console has red exceptions. Does the test not see them?

A checkout test passes every day. Meanwhile the page throws a TypeError in a recommendations widget and a background analytics request returns 500. A user does not notice, and neither does the test: it checks only what it was told to check. A month later the same exception touches the "Pay" button, and it turns out the warning had been visible for a long time. This lesson covers how to make a test see browser errors without making it brittle.

How it works and why. Playwright delivers page events to subscribed handlers. Four matter for diagnostics:

  • page.on('console', msg => …): console.* calls; msg.type() returns 'error', 'warning', 'log', msg.text() the text, msg.location() the script URL and line.
  • page.on('pageerror', err => …): unhandled exceptions on the page.
  • page.on('requestfailed', req => …): network failures (a reset, DNS), but not 4xx/5xx responses.
  • page.on('response', res => …): all responses; filter on status() >= 500.

The main limitation: an event is delivered only to those already subscribed. Errors that occurred while the page was loading will not be seen by a handler added after page.goto(). Since Playwright 1.56 already received messages can be read back with page.consoleMessages() and page.pageErrors() (up to the last 200), but this is a safety net, not a replacement for subscribing before navigation. So the check is made an auto fixture: it subscribes before the first goto in every test and checks the result at teardown.

When to subscribe

Wrong

After page.goto()

Load-time errors have already passed. The test is green although an exception occurred.

Right

An auto fixture before navigation

The handler is in place before the first request. The rule applies to all tests without duplication.

Figure 1. The order "subscribe, then navigate" decides whether the test sees early errors.

Example: from a hidden exception to a rule in all tests. A test that lets an error through:

test('checkout', async ({ page }) => {
  await page.goto('/checkout');          // load-time errors already passed
  page.on('pageerror', (e) => errors.push(e.message));
  await page.getByRole('button', { name: 'Pay' }).click();
  await expect(page.getByText('Thank you')).toBeVisible();
});

The handler is added after goto, so exceptions during loading are lost, and nobody checks the accumulated array. The fix: a fixture with a parameter for allowed exceptions.

import { test as base, expect } from '@playwright/test';

export const test = base.extend<{
  allowedErrors: RegExp[];
  browserErrors: string[];
}>({
  allowedErrors: [[], { option: true }],
  browserErrors: [
    async ({ page, allowedErrors }, use) => {
      const errors: string[] = [];
      const keep = (s: string) => !allowedErrors.some((re) => re.test(s));
      page.on('pageerror', (e) => {
        if (keep(e.message)) errors.push(e.message);
      });
      page.on('console', (m) => {
        if (m.type() === 'error' && keep(m.text()))
          errors.push(m.text() + ' @ ' + m.location().url);
      });
      await use(errors);
      expect(errors, 'unexpected browser errors').toEqual([]);
    },
    { auto: true },
  ],
});

After await use(errors) the test has already finished, and the check in the fixture teardown fails it if the array has anything. The allowedErrors option lets you narrow the check for a file or a project:

// known noise of a third-party analytics script: narrow and explained
test.use({ allowedErrors: [/analytics\.example\.com/] });

// a negative scenario: the error is allowed only here
test.describe('payment failure', () => {
  test.use({ allowedErrors: [/status of 500/] });

  test('shows a message', async ({ page }) => {
    await page.route('**/api/pay', (r) => r.fulfill({ status: 500 }));
    // ...
  });
});

Why this way: the allowlist is narrow (a specific domain, not "anything containing error") and explained. Negative scenarios where the error is expected remove noise locally instead of switching the check off everywhere. For known noise from a certain resource (for example a 404 on a favicon) filter by the address from msg.location().url.

Limits and alternatives. page.on listens to one page. For popups and new tabs subscribe at the context level (context.on('console'), context.on('page')) and add handlers to each new page. Errors in an iframe reach the page, while exceptions in workers or extensions may not. The fixture catches only what happened in this run, so it complements functional checks and does not replace them. In Cypress a similar role is played by cy.on('uncaught:exception'), but by default Cypress itself fails a test on an unhandled application exception, whereas Playwright requires a subscription.

Typical mistakes.

  • Subscribing after goto: early errors vanish.
  • A broad allowlist "so it does not turn red": the check catches nothing.
  • Collecting an array and not checking it: errors exist in memory but the test is green.
  • Switching the fixture off entirely for a negative scenario instead of expecting the error precisely.

Check yourself

The fixture checks errors after await use(errors). Why not inside the test?

Answer

The rule must apply to every test automatically and not depend on whether the test author remembered to call it. The fixture teardown runs after the test body, so everything that happened throughout the test is already collected, and it fails the test if there are errors.

A popup opens in a test and an exception occurs in it. Will the page.on('pageerror') handler of the main page see it?

Answer

No, a popup is a separate page and its events go to its own handlers. Subscribe at the context level through context.on('page') and add handlers to each new page, or listen to context.on('console') for console messages of all pages.

In an interview. Junior: I listen to page.on('console') and page.on('pageerror'), collect errors and check there are none. I subscribe before navigating to the page. Middle/Senior: I make it an auto fixture with a narrow allowlist as an option so the rule applies to all tests and does not break on known noise. For popups I subscribe on the context. I know that since Playwright 1.56 early messages can be read back through page.consoleMessages(), but I do not replace subscribing before navigation with it.

More articles in this chapter