On this page
[Best practices]
Error handling
A test suite that stops dead on the first timeout tells you nothing. These are the patterns that make a failure legible: retry what is genuinely flaky, recover what can be recovered, and record enough about the rest that nobody has to reproduce it by hand. The code is plain Playwright and runs wherever you run your tests.
Basic Error Handling Patterns
Custom Error Classes
typescript
import { test, errors, type Page } from '@playwright/test';
// Custom error classes for better error handling
class TestError extends Error {
context: Record<string, unknown>;
timestamp = new Date().toISOString();
constructor(message: string, context: Record<string, unknown> = {}) {
super(message);
this.name = 'TestError';
this.context = context;
}
}
class ElementNotFoundError extends TestError {
selector: string;
timeout: number;
constructor(selector: string, timeout = 10000) {
super(`Element not found: ${selector} after ${timeout}ms`, { selector, timeout });
this.name = 'ElementNotFoundError';
this.selector = selector;
this.timeout = timeout;
}
}
class ValidationError extends TestError {
constructor(expected: string, actual: string, field: string) {
super(`Validation failed for ${field}: expected "${expected}", got "${actual}"`, { expected, actual, field });
this.name = 'ValidationError';
}
}
class NetworkError extends TestError {
constructor(url: string, statusCode: number, message: string) {
super(`Network request failed: ${url} - ${statusCode} ${message}`, { url, statusCode });
this.name = 'NetworkError';
}
}
// Usage in tests
async function waitForElement(page: Page, selector: string, timeout = 10000) {
const element = page.locator(selector);
try {
await element.waitFor({ state: 'visible', timeout });
} catch (error) {
// Playwright throws a TimeoutError when the element never shows up
if (error instanceof errors.TimeoutError) {
throw new ElementNotFoundError(selector, timeout);
}
throw error;
}
return element;
}
// Test with custom errors
test('should validate form submission', async ({ page }) => {
try {
const response = await page.goto('https://example.com/contact');
if (!response?.ok()) {
throw new NetworkError(page.url(), response?.status() ?? 0, response?.statusText() ?? 'no response');
}
const submitButton = await waitForElement(page, '#submit-btn');
await submitButton.click();
const successMessage = await waitForElement(page, '.success');
const actualText = (await successMessage.innerText()).trim();
if (actualText !== 'Form submitted successfully') {
throw new ValidationError('Form submitted successfully', actualText, 'success message');
}
} catch (error) {
if (error instanceof ElementNotFoundError) {
console.error('UI element missing:', error.selector);
// Handle specific element not found scenario
} else if (error instanceof ValidationError) {
console.error('Validation failed:', error.context);
// Handle validation errors
} else if (error instanceof NetworkError) {
console.error('Page failed to load:', error.context);
}
throw error;
}
});Error Wrapper Functions
typescript
import { test, expect, errors, type Page } from '@playwright/test';
// Generic error wrapper
async function withErrorHandling<T>(page: Page, fn: () => Promise<T>, errorMessage: string): Promise<T> {
try {
return await fn();
} catch (error) {
console.error(`${errorMessage}:`, error);
// Capture additional context
const context = {
url: page.url(),
title: await page.title().catch(() => null),
timestamp: new Date().toISOString(),
};
// Attach the context and a screenshot to the test report
await test.info().attach('error context', {
body: JSON.stringify(context, null, 2),
contentType: 'application/json',
});
const screenshot = await page.screenshot().catch(() => null);
if (screenshot) {
await test.info().attach('screenshot', { body: screenshot, contentType: 'image/png' });
}
// Attach context to error
throw Object.assign(error as Error, { context });
}
}
interface RetryOptions {
maxAttempts?: number;
delay?: number;
backoff?: number;
retryIf?: (error: unknown) => boolean;
}
// Retry wrapper with exponential backoff
async function withRetry<T>(fn: () => Promise<T>, options: RetryOptions = {}): Promise<T> {
const { maxAttempts = 3, delay = 1000, backoff = 2, retryIf = () => true } = options;
let lastError: unknown;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error;
if (attempt === maxAttempts || !retryIf(error)) {
throw error;
}
const waitTime = delay * Math.pow(backoff, attempt - 1);
console.log(`Attempt ${attempt} failed, retrying in ${waitTime}ms...`);
await new Promise((resolve) => setTimeout(resolve, waitTime));
}
}
throw lastError;
}
// Safe element interaction wrapper
async function safeClick(page: Page, selector: string, options: { retries?: number } = {}) {
return withErrorHandling(page, async () => {
return withRetry(async () => {
// click() itself waits for the element to be visible, enabled and not covered
await page.locator(selector).click({ timeout: 5000 });
}, {
maxAttempts: options.retries ?? 3,
retryIf: (error) => error instanceof errors.TimeoutError,
});
}, `Failed to click element: ${selector}`);
}
// Usage in tests
test('should complete checkout flow', async ({ page }) => {
await page.goto('https://example.com/shop');
await safeClick(page, '#add-to-cart');
await safeClick(page, '#checkout-btn');
// Playwright's own retry for a block of assertions
await expect(async () => {
const total = await page.locator('.order-total').innerText();
expect(parseFloat(total.replace('$', ''))).toBeGreaterThan(0);
}).toPass({
intervals: [500, 1000, 2000],
timeout: 10000,
});
});