Playwright + JS · Lesson 6 of 35

0/35 done

Module 6: Error Handling

6. Error Handling & Custom Exceptions

12 minlesson

Try it yourself

Implement safeExecuteWithFallback:

  1. Accept primaryAction and fallbackAction async functions.
  2. Try executing primaryAction(). If it throws, execute fallbackAction() and return its result.

The editor has a worked example. Read it, tweak it, then press Mark as complete.

Try, Catch, Finally & Custom Errors

javascript
export class AutomationTimeoutError extends Error {
  constructor(message) {
    super(message);
    this.name = "AutomationTimeoutError";
  }
}

async function safeClick(action) {
  try {
    await action();
  } catch (error) {
    console.warn("Non-fatal element click failed, continuing:", error.message);
  } finally {
    console.log("Cleanup hook executed");
  }
}

Key Takeaways & Walkthrough Summary

Automated tests interact with dynamic web servers where network timeouts, dialogs, and missing elements happen. In this lesson, we will master error handling using try, catch, finally, and custom error classes to build resilient test runners. Let's dive in!

Part of the Playwright + JS course (Playwright with JavaScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Should test assertions be caught inside try/catch blocks?

No! Assertion errors must throw up to the test runner so failed assertions mark the test as failed. Use try/catch only for optional elements or cleanup logic.

Finished reading?

Review the worked example in the editor, then mark the lesson complete.

JavaScript
Skip