Skip to content

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

fix(async): avoid re-raising task callback errors

GautamSharma99ac1536257686
diff --git a/browser_use/utils.py b/browser_use/utils.py
index 6298e66f9..b362f247d 100644
--- a/browser_use/utils.py
+++ b/browser_use/utils.py
@@ -802,9 +802,8 @@ def create_task_with_error_handling(
coro: The coroutine to wrap in a task
name: Optional name for the task (useful for debugging)
logger_instance: Optional logger instance to use. If None, uses module logger.
- suppress_exceptions: If True, logs exceptions at ERROR level. If False, logs at WARNING level
- and exceptions remain retrievable via task.exception() if the caller awaits the task.
- Default False.
+ suppress_exceptions: If True, logs exceptions at ERROR level. If False, logs at WARNING level.
+ Awaiting the task raises the original exception in both modes. Default False.
Returns:
asyncio.Task: The created task with exception handling callback
@@ -822,21 +821,19 @@ 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
+ # Retrieve the exception so fire-and-forget tasks do not emit
+ # "Task exception was never retrieved" warnings.
exc = t.exception()
if exc is not None:
task_name = t.get_name() if hasattr(t, 'get_name') else 'unnamed'
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 mark for re-raising
log.warning(
f'Exception in background task [{task_name}]: {type(exc).__name__}: {exc}',
exc_info=exc,
)
- exc_to_raise = exc
except asyncio.CancelledError:
# Task was cancelled, this is normal behavior
pass
@@ -845,10 +842,6 @@ 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
diff --git a/tests/ci/test_async_task_error_handling.py b/tests/ci/test_async_task_error_handling.py
new file mode 100644
index 000000000..d936a1671
--- /dev/null
+++ b/tests/ci/test_async_task_error_handling.py
@@ -0,0 +1,50 @@
+import asyncio
+import logging
+from unittest.mock import Mock
+
+import pytest
+
+from browser_use.utils import create_task_with_error_handling
+
+
+class ExpectedTaskError(RuntimeError):
+ """Exception used to verify task propagation."""
+
+
[email protected]('suppress_exceptions', [False, True])
+async def test_task_exception_is_not_reported_as_callback_failure(suppress_exceptions: bool) -> None:
+ loop = asyncio.get_running_loop()
+ previous_exception_handler = loop.get_exception_handler()
+ exception_contexts: list[dict] = []
+ test_logger = Mock(spec=logging.Logger)
+
+ def capture_loop_exception(_loop: asyncio.AbstractEventLoop, context: dict) -> None:
+ exception_contexts.append(context)
+
+ async def fail() -> None:
+ raise ExpectedTaskError('expected failure')
+
+ loop.set_exception_handler(capture_loop_exception)
+ try:
+ task = create_task_with_error_handling(
+ fail(),
+ name='expected-failure',
+ logger_instance=test_logger,
+ suppress_exceptions=suppress_exceptions,
+ )
+
+ with pytest.raises(ExpectedTaskError, match='expected failure'):
+ await task
+
+ # Let all callbacks queued by task completion run.
+ await asyncio.sleep(0)
+ finally:
+ loop.set_exception_handler(previous_exception_handler)
+
+ assert exception_contexts == []
+ if suppress_exceptions:
+ test_logger.error.assert_called_once()
+ test_logger.warning.assert_not_called()
+ else:
+ test_logger.warning.assert_called_once()
+ test_logger.error.assert_not_called()