Skip to content

add try/except around event handling #402

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 17, 2021
Merged
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 src/idom/core/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,10 @@ async def dispatch(self, event: LayoutEvent) -> None:
handler = self._event_handlers.get(event.target)

if handler is not None:
await handler(event.data)
try:
await handler(event.data)
except Exception:
logger.exception(f"Failed to execute event handler {handler}")
else:
logger.info(
f"Ignored event - handler {event.target!r} does not exist or its component unmounted"
Expand Down
25 changes: 24 additions & 1 deletion tests/test_core/test_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ def use_toggle(init=False):
return state, lambda: set_state(lambda old: not old)


async def test_model_key_preserves_callback_identity_for_common_elements():
async def test_model_key_preserves_callback_identity_for_common_elements(caplog):
called_good_trigger = idom.Ref(False)
good_handler = StaticEventHandler()
bad_handler = StaticEventHandler()
Expand Down Expand Up @@ -330,6 +330,8 @@ def bad_trigger():

await layout.render()

assert not caplog.records


async def test_model_key_preserves_callback_identity_for_components():
called_good_trigger = idom.Ref(False)
Expand Down Expand Up @@ -495,3 +497,24 @@ def SomeComponent():
next(iter(caplog.records)).message
== f"Did not render component - {component_not_in_layout} already unmounted or does not belong to this layout"
)


async def test_log_error_on_bad_event_handler(caplog):
bad_handler = StaticEventHandler()

@idom.component
def ComponentWithBadEventHandler():
@bad_handler.use
def raise_error():
raise Exception("bad event handler")

return idom.html.button({"onClick": raise_error})

with idom.Layout(ComponentWithBadEventHandler()) as layout:
await layout.render()
event = LayoutEvent(bad_handler.target, [])
await layout.dispatch(event)

assert next(iter(caplog.records)).message.startswith(
"Failed to execute event handler"
)