Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion playwright/_impl/_greenlets.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import greenlet

from playwright._impl._errors import TargetClosedError
from playwright._impl.utils.tasks import CONTROL_FLOW_EXCEPTIONS


def _greenlet_trace_callback(
Expand Down Expand Up @@ -80,7 +81,9 @@ def run_in_greenlet(
def body() -> None:
try:
future.set_result(func())
except Exception as e:
except CONTROL_FLOW_EXCEPTIONS:
raise
except BaseException as e:
future.set_exception(e)

greenlet_class(body).switch()
Expand Down
16 changes: 11 additions & 5 deletions playwright/_impl/channel_owner.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,11 @@
show_internal_stack_frames,
stringify_stack_frames,
)
from playwright._impl.utils.tasks import failed, fire_and_forget
from playwright._impl.utils.tasks import (
CONTROL_FLOW_EXCEPTIONS,
failed,
fire_and_forget,
)
from playwright._impl.utils.zones import current_zone

if TYPE_CHECKING: # pragma: no cover
Expand All @@ -80,7 +84,7 @@ def __init__(
self.reported = False
self.user_data: Any = None
self.call_id: Optional[str] = None
self.error: Optional[Exception] = None
self.error: Optional[BaseException] = None

def options(self) -> Dict[str, Any]:
# Python: `{ ...apiZone }` in the options of sendMessageToServer().
Expand Down Expand Up @@ -157,7 +161,9 @@ def func(api_zone: ApiZone) -> Awaitable[Any]:
# option, which is enough.
try:
result = owner._wrap_api_call(func, ApiCallOptions(internal=is_internal))
except Exception as e:
except CONTROL_FLOW_EXCEPTIONS:
raise
except BaseException as e:
return failed(e)
if mapper is None:
return result
Expand Down Expand Up @@ -354,14 +360,14 @@ async def finish() -> R:
log_api_call(logger, f"<= {api_zone.api_name} succeeded")
self._instrumentation.on_api_call_end(api_zone)
return result
except asyncio.CancelledError:
except CONTROL_FLOW_EXCEPTIONS:
# Python: the task that awaits the call was cancelled, and the call
# is aborted; upstream sees an AbortError.
if not (options and options.internal):
log_api_call(logger, f"<= {api_zone.api_name} failed")
self._instrumentation.on_api_call_end(api_zone)
raise
except Exception as e:
except BaseException as e:
stack = getattr(e, "_stack", None)
inner_error = (
"\n<inner error>\n" + stack
Expand Down
10 changes: 8 additions & 2 deletions playwright/_impl/connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,11 @@
from playwright._impl.isomorphic.string_utils import js_string
from playwright._impl.isomorphic.time import monotonic_time
from playwright._impl.timeout_settings import NO_TIMEOUT
from playwright._impl.utils.tasks import call_in_next_task, fire_and_forget
from playwright._impl.utils.tasks import (
CONTROL_FLOW_EXCEPTIONS,
call_in_next_task,
fire_and_forget,
)

if TYPE_CHECKING: # pragma: no cover
from playwright._impl.local_utils import LocalUtils
Expand Down Expand Up @@ -164,7 +168,9 @@ def on_message(message: Dict[str, Any]) -> None:
nonlocal close_error
try:
connection.dispatch(message)
except Exception as e:
except CONTROL_FLOW_EXCEPTIONS:
raise
except BaseException as e:
# Python: String(e) is the name and the message of the error.
close_error = f"{e.name if isinstance(e, Error) else type(e).__name__}: {e}"
fire_and_forget(transport.close())
Expand Down
8 changes: 2 additions & 6 deletions playwright/_impl/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@
)
from playwright._impl.errors import (
Error,
PlaywrightError,
TargetClosedError,
parse_error,
)
Expand Down Expand Up @@ -319,11 +318,8 @@ def dispatch(self, message: Dict[str, Any]) -> None:
if error and not result:
parsed_error = parse_error(error)
parsed_error._log = log or []
parsed_error = cast(
PlaywrightError,
rewrite_error_message(
parsed_error, parsed_error.message + format_call_log(log)
),
parsed_error = rewrite_error_message(
parsed_error, parsed_error.message + format_call_log(log)
)
details_validator = maybe_find_validator(
callback.type, callback.method, "ErrorDetails"
Expand Down
10 changes: 7 additions & 3 deletions playwright/_impl/event_emitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
from typing import Any, Callable, Dict, List, Optional, Set, Union

from playwright._impl.utils.debug import is_under_test
from playwright._impl.utils.tasks import completed
from playwright._impl.utils.tasks import CONTROL_FLOW_EXCEPTIONS, completed

EventType = str
Listener = Callable[..., Any]
Expand Down Expand Up @@ -88,7 +88,9 @@ def _call_handler(self, type: EventType, handler: Listener, args: Any) -> None:
return
# Python: an awaitable is the counterpart of a JS promise or thenable.
future = asyncio.ensure_future(promise)
except Exception as error:
except CONTROL_FLOW_EXCEPTIONS:
raise
except BaseException as error:
self._handle_listener_error(type, error)
return
pending = self._pending_handlers.get(type)
Expand All @@ -109,7 +111,9 @@ def on_done(f: "asyncio.Future[Any]") -> None:
else:
try:
self._handle_listener_error(type, e)
except Exception as error:
except CONTROL_FLOW_EXCEPTIONS:
raise
except BaseException as error:
# Python: report an unhandled rejection outside the task callback.
self._report_unhandled_error(error)

Expand Down
10 changes: 8 additions & 2 deletions playwright/_impl/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,11 @@
)
from playwright._impl.timeout_settings import NO_TIMEOUT
from playwright._impl.utils.stack_trace import rewrite_error_message
from playwright._impl.utils.tasks import completed, fire_and_forget
from playwright._impl.utils.tasks import (
CONTROL_FLOW_EXCEPTIONS,
completed,
fire_and_forget,
)
from playwright._impl.utils.zones import Zone, current_zone
from playwright._impl.waiter import Waiter

Expand Down Expand Up @@ -1276,7 +1280,9 @@ async def _handle_impl(self, route: Route) -> bool:
self._active_invocations.add(handler_invocation)
try:
return await self._handle_internal(route)
except Exception as e:
except CONTROL_FLOW_EXCEPTIONS:
raise
except BaseException as e:
# If the handler was stopped (without waiting for completion), we ignore all exceptions.
if self._ignore_exception:
return False
Expand Down
5 changes: 4 additions & 1 deletion playwright/_impl/out_of_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
from playwright._impl.connection import Connection
from playwright._impl.playwright import Playwright
from playwright._impl.transport import PipeTransport
from playwright._impl.utils.tasks import CONTROL_FLOW_EXCEPTIONS


async def start() -> Tuple[Playwright, "PlaywrightClient"]:
Expand All @@ -50,7 +51,9 @@ def on_message(message: Any) -> None:
# call raises it, and the transport goes on.
try:
connection.dispatch(message)
except Exception as error:
except CONTROL_FLOW_EXCEPTIONS:
raise
except BaseException as error:
connection._on_event_listener_error(error)

transport.on_message = on_message
Expand Down
6 changes: 4 additions & 2 deletions playwright/_impl/page.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@
)
from playwright._impl.screencast import Screencast
from playwright._impl.timeout_settings import NO_TIMEOUT, TimeoutSettings
from playwright._impl.utils.tasks import fire_and_forget
from playwright._impl.utils.tasks import CONTROL_FLOW_EXCEPTIONS, fire_and_forget
from playwright._impl.video import Video
from playwright._impl.waiter import Waiter
from playwright._impl.web_storage import WebStorage
Expand Down Expand Up @@ -1882,7 +1882,9 @@ async def call(self, func: Callable[..., Any]) -> None:
result=serialize_argument(_to_impl(result)), timeout=NO_TIMEOUT
)
)
except Exception as e:
except CONTROL_FLOW_EXCEPTIONS:
raise
except BaseException as e:
fire_and_forget(
self._channel.reject(error=serialize_error(e), timeout=NO_TIMEOUT)
)
Expand Down
6 changes: 4 additions & 2 deletions playwright/_impl/utils/stack_trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,14 @@
import sys
import sysconfig
from types import FrameType
from typing import List, Optional, Tuple, TypedDict
from typing import List, Optional, Tuple, TypedDict, TypeVar

import playwright
from playwright._impl.errors import Error
from playwright._impl.utils.debug import get_as_boolean_from_env

E = TypeVar("E", bound=BaseException)


class StackFrame(TypedDict, total=False):
file: str
Expand Down Expand Up @@ -71,7 +73,7 @@ def _sync_caller_frame() -> Optional[FrameType]:
return getattr(task, "__pw_caller_frame__", None)


def rewrite_error_message(e: Exception, new_message: str) -> Exception:
def rewrite_error_message(e: E, new_message: str) -> E:
"""Port of rewriteErrorMessage().

Python: upstream changes the error itself; this changes a copy, because the same
Expand Down
12 changes: 12 additions & 0 deletions playwright/_impl/utils/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,20 @@
import asyncio
from typing import Any, Awaitable, Callable, List, Sequence, Set, TypeVar

from greenlet import GreenletExit

T = TypeVar("T")

# Control-flow BaseExceptions that must pass through untouched rather than
# being caught as listener or user-handler failures (unlike e.g. pytest.fail()).
CONTROL_FLOW_EXCEPTIONS = (
KeyboardInterrupt,
SystemExit,
GeneratorExit,
asyncio.CancelledError,
GreenletExit,
)

# The tasks of fire_and_forget(): the event loop keeps only weak references.
_tasks: Set["asyncio.Future[Any]"] = set()

Expand Down
24 changes: 17 additions & 7 deletions playwright/_impl/waiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,12 @@
from playwright._impl.errors import TimeoutError
from playwright._impl.utils.crypto import create_guid
from playwright._impl.utils.stack_trace import rewrite_error_message
from playwright._impl.utils.tasks import completed, fire_and_forget, race
from playwright._impl.utils.tasks import (
CONTROL_FLOW_EXCEPTIONS,
completed,
fire_and_forget,
race,
)
from playwright._impl.utils.zones import Zone, current_zone

if TYPE_CHECKING: # pragma: no cover
Expand Down Expand Up @@ -185,15 +190,16 @@ async def wait_for_promise(
if dispose:
dispose()
return result
except asyncio.CancelledError:
except CONTROL_FLOW_EXCEPTIONS as e:
# Python: the task that waits was cancelled, for example by an expect_*()
# block that raised. Clean up as for an error.
if dispose:
dispose()
self._error = "The operation was aborted"
if isinstance(e, asyncio.CancelledError):
self._error = "The operation was aborted"
self.dispose()
raise
except Exception as e:
except BaseException as e:
if dispose:
dispose()
self._error = str(e)
Expand Down Expand Up @@ -240,7 +246,7 @@ def settle(matched: bool) -> None:
if not promise.done():
promise.set_result(event_arg)

def fail(e: Exception) -> None:
def fail(e: BaseException) -> None:
emitter.remove_listener(event, listener)
if not promise.done():
promise.set_exception(e)
Expand All @@ -256,13 +262,17 @@ def run() -> Any:
async def continuation() -> None:
try:
settle(bool(await matched))
except Exception as e:
except CONTROL_FLOW_EXCEPTIONS:
raise
except BaseException as e:
fail(e)

# Python: started here, so that it runs in the saved zone.
return asyncio.ensure_future(continuation())
settle(bool(matched))
except Exception as e:
except CONTROL_FLOW_EXCEPTIONS:
raise
except BaseException as e:
fail(e)
return None

Expand Down
Loading