Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

refactor: refine exception propagation in create_task_with_error_handling

reformedotbc8407ac8de0
diff --git a/browser_use/utils.py b/browser_use/utils.py
index c7fe381bd..6fc2a5557 100644
--- a/browser_use/utils.py
+++ b/browser_use/utils.py
@@ -704,6 +704,7 @@ def create_task_with_error_handling(
def _handle_task_exception(t: asyncio.Task[T]) -> None:
"""Callback to handle task exceptions"""
+ exc_to_raise = None
try:
# This will raise if the task had an exception
exc = t.exception()
@@ -712,12 +713,12 @@ def create_task_with_error_handling(
if suppress_exceptions:
log.error(f'Exception in background task [{task_name}]: {type(exc).__name__}: {exc}', exc_info=exc)
else:
- # Log at warning level then re-raise to propagate to event loop's exception handler
+ # Log at warning level then mark for re-raising
log.warning(
f'Exception in background task [{task_name}]: {type(exc).__name__}: {exc}',
exc_info=exc,
)
- raise exc
+ exc_to_raise = exc
except asyncio.CancelledError:
# Task was cancelled, this is normal behavior
pass
@@ -726,5 +727,9 @@ def create_task_with_error_handling(
task_name = t.get_name() if hasattr(t, 'get_name') else 'unnamed'
log.error(f'Error handling exception in task [{task_name}]: {type(e).__name__}: {e}')
+ # Re-raise outside the try-except block so it propagates to the event loop
+ if exc_to_raise is not None:
+ raise exc_to_raise
+
task.add_done_callback(_handle_task_exception)
return task