Prompt
How do I build exception handling into a browser automation flow?
Latest observation
A good browser automation flow should treat exceptions as a normal part of execution, not an edge case. The goal is to make failures visible, recoverable when possible, and safe to resume or abort cleanly.
1) Identify likely failure points
Typical browser automation exceptions come from:
- Page not loaded or navigation timed out
- Elements not found
- Elements found but not interactable
- Stale element references after DOM updates
- Popups, alerts, or modals blocking interaction
- Authentication/session expiry
- Network failures or server errors
- Unexpected redirects or changed page structure
2) Wrap each meaningful step
Instead of one huge try/catch around the whole flow, structure your automation into steps:
- open page
- log in
- navigate
- fill form
- submit
- verify result
Then handle exceptions per step so you know exactly where it failed.
Example pattern
try:
open_page()
login()
navigate_to_target()
fill_form()
submit()
verify_success()
except TimeoutError as e:
log_error("Timed out waiting for page or element", e)
take_screenshot()
recover_or_abort()
except NoSuchElementException as e:
log_error("Missing expected element", e)
take_screenshot()
abort()
except Exception as e:
log_error("Unexpected failure", e)
take_screenshot()
abort()
finally:
cleanup()
3) Use retries only where they make sense
Not every exception should be retried.
Good candidates for retry:
- Temporary network failures
- Transient timeouts
- Stale element errors
- Click intercepted by a loading overlay
Poor candidates for retry:
- Wrong locator
- Invalid credentials
- Missing required data
A simple retry strategy:
- retry 2–3 times
- add small backoff delays
- re-locate the element before retrying if the DOM may have changed
4) Prefer explicit waits over fixed sleeps
Many “exceptions” are actually timing issues.
Use:
- wait until element is visible
- wait until clickable
- wait until page/network state is stable
Avoid relying on hardcoded sleep() unless absolutely necessary.
5) Capture diagnostics on failure
When something fails, record enough context to debug it later:
- Screenshot
- HTML snapshot or DOM excerpt
- Current URL
- Browser console logs
- Network logs if available
- Step name and timestamp
- Input data used for that run
This makes failures actionable instead of mysterious.
6) Make cleanup unconditional
Always clean up browser resources in a finally block or equivalent:
- close tabs
- quit browser session
- release temp files
- reset test data if needed
This prevents orphaned browser processes and stale sessions.
7) Separate recoverable and fatal errors
Design your handler to classify exceptions:
Recoverable
- element temporarily unavailable
- transient page load issue
- modal dismissed and retry possible
Fatal
- login failed
- account locked
- required selector changed
- broken business rule
Recoverable errors can retry or fallback. Fatal errors should stop the flow and surface clearly.
8) Log with step context
Instead of generic messages, log like this:
- Step:
login - Action:
click submit - Result:
Timeout waiting for button - Retry count:
1
This helps you pinpoint whether the failure is in navigation, selectors, timing, or app behavior.
9) Build a reusable helper layer
A common pattern is to centralize exception handling in helpers like:
safe_click(selector)safe_type(selector, text)safe_wait(selector, condition)run_step(name, fn)
That keeps your main flow readable and ensures consistent handling.
Example helper idea
def run_step(name, fn):
try:
return fn()
except Exception as e:
log_error(f"Step failed: {name}", e)
take_screenshot(name)
raise
10) Decide what the automation should do after failure
Your flow should define a policy:
- abort immediately
- retry the step
- refresh the page and continue
- re-authenticate and resume
- mark the run failed and notify someone
Without a policy, exception handling becomes inconsistent.
If you want, I can show you a concrete exception-handling template in Selenium, Playwright, or Puppeteer.