Skip to content

Commit

Permalink
Merge pull request #1130 from max-muoto/fix-exception-typing
Browse files Browse the repository at this point in the history
Fix typing for Exception Handlers
  • Loading branch information
vitalik committed Apr 30, 2024
2 parents d9bda3a + 9498fc0 commit 5b10511
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions ninja/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
Sequence,
Tuple,
Type,
TypeVar,
Union,
)

Expand All @@ -34,8 +35,9 @@

__all__ = ["NinjaAPI"]

Exc = Union[Exception, Type[Exception]]
ExcHandler = Callable[[HttpRequest, Exc], HttpResponse]
_E = TypeVar("_E", bound=Exception)
Exc = Union[_E, Type[_E]]
ExcHandler = Callable[[HttpRequest, Exc[_E]], HttpResponse]


class NinjaAPI:
Expand Down Expand Up @@ -468,7 +470,7 @@ def get_operation_url_name(self, operation: "Operation", router: Router) -> str:
return operation.view_func.__name__

def add_exception_handler(
self, exc_class: Type[Exception], handler: ExcHandler
self, exc_class: Type[_E], handler: ExcHandler[_E]
) -> None:
assert issubclass(exc_class, Exception)
self._exception_handlers[exc_class] = handler
Expand All @@ -483,13 +485,13 @@ def decorator(func: Callable) -> Callable:
def set_default_exception_handlers(self) -> None:
set_default_exc_handlers(self)

def on_exception(self, request: HttpRequest, exc: Exc) -> HttpResponse:
def on_exception(self, request: HttpRequest, exc: Exc[_E]) -> HttpResponse:
handler = self._lookup_exception_handler(exc)
if handler is None:
raise exc
return handler(request, exc)

def _lookup_exception_handler(self, exc: Exc) -> Optional[ExcHandler]:
def _lookup_exception_handler(self, exc: Exc[_E]) -> Optional[ExcHandler[_E]]:
for cls in type(exc).__mro__:
if cls in self._exception_handlers:
return self._exception_handlers[cls]
Expand Down

0 comments on commit 5b10511

Please sign in to comment.