Playwright + TS · Lesson 9 of 36
Module 9: Error Handling
Your task
Wrap the async operation in a try/catch block. In catch, print the error message and re-throw the error.
Write it in the editor, then press Check answer (Ctrl + Enter).
export class LocatorTimeoutError extends Error {
constructor(locatorName: string, timeoutMs: number) {
super(`Element '${locatorName}' did not appear within ${timeoutMs}ms`);
this.name = "LocatorTimeoutError";
}
}
async function safeClick(action: () => Promise<void>) {
try {
await action();
} catch (error) {
console.error("Action failed:", (error as Error).message);
throw error; // Re-throw to fail the test properly
} finally {
console.log("Cleanup executed");
}
}Automated tests run in dynamic web environments where network blips and missing elements can happen. In this lesson, we will master error handling using try, catch, and finally blocks, custom error classes, and asynchronous error handling. You will learn how to handle unexpected failures gracefully. Let's dive in!
Part of the Playwright + TS course (Playwright with TypeScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.
If you catch an error and do not re-throw it, the test runner thinks the test passed! Re-throwing ensures errors are logged while allowing the test runner to fail the test.
Ready? Solve the task in the editor
Use Check answer to mark it complete. Hints are there if you need them.
___