Skip to content

Commit

Permalink
Improve exception handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Garulf committed Feb 16, 2024
1 parent a829da2 commit 1ef9e6e
Showing 1 changed file with 21 additions and 7 deletions.
28 changes: 21 additions & 7 deletions pyflowlauncher/event.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import asyncio
from typing import Any, Callable, Iterable, Type
from typing import Any, Callable, Iterable, Type, Union


class EventNotFound(Exception):

def __init__(self, event: str):
self.event = event
super().__init__(f"Event '{event}' not found.")


class EventHandler:
Expand All @@ -8,7 +15,7 @@ def __init__(self):
self._events = {}
self._handlers = {}

def _get_callable_name(self, method: Callable[..., Any]):
def _get_callable_name(self, method: Union[Callable[..., Any], Exception]):
return getattr(method, '__name__', method.__class__.__name__).lower()

def add_event(self, event: Callable[..., Any], *, name=None) -> str:
Expand All @@ -24,19 +31,26 @@ def add_exception_handler(self, exception: Type[Exception], handler: Callable[..
self._handlers[exception] = handler

def get_event(self, event: str) -> Callable[..., Any]:
return self._events[event]
try:
return self._events[event]
except KeyError:
raise EventNotFound(event)

async def _await_maybe(self, result: Any) -> Any:
if asyncio.iscoroutine(result):
return await result
return result

async def trigger_exception_handler(self, exception: Exception) -> Any:
try:
handler = self._handlers[exception.__class__]
return await self._await_maybe(handler(exception))
except KeyError:
raise exception

async def trigger_event(self, event: str, *args, **kwargs) -> Any:
try:
result = self.get_event(event)(*args, **kwargs)
return await self._await_maybe(result)
except Exception as e:
handler = self._handlers.get(type(e), None)
if handler:
return handler(e)
raise e
return await self.trigger_exception_handler(e)

0 comments on commit 1ef9e6e

Please sign in to comment.