Skip to content

Commit

Permalink
add try/except around event handling
Browse files Browse the repository at this point in the history
  • Loading branch information
rmorshea committed Jun 17, 2021
1 parent 2b7f485 commit f2bf589
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
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"
)

0 comments on commit f2bf589

Please sign in to comment.