|
| 1 | +import functools |
| 2 | +import logging |
| 3 | +from collections.abc import Callable, Iterable |
| 4 | +from contextlib import AbstractAsyncContextManager |
| 5 | +from types import TracebackType |
| 6 | +from typing import Protocol, TypeAlias |
| 7 | + |
| 8 | +from aiohttp import web |
| 9 | +from servicelib.aiohttp.typing_extension import Handler as WebHandler |
| 10 | +from servicelib.aiohttp.typing_extension import Middleware as WebMiddleware |
| 11 | + |
| 12 | +_logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | + |
| 15 | +class AiohttpExceptionHandler(Protocol): |
| 16 | + __name__: str |
| 17 | + |
| 18 | + async def __call__( |
| 19 | + self, |
| 20 | + request: web.Request, |
| 21 | + exception: Exception, |
| 22 | + ) -> web.StreamResponse: |
| 23 | + """ |
| 24 | + Callback that handles an exception produced during a request and transforms it into a response |
| 25 | +
|
| 26 | + Arguments: |
| 27 | + request -- current request |
| 28 | + exception -- exception raised in web handler during this request |
| 29 | + """ |
| 30 | + |
| 31 | + |
| 32 | +ExceptionHandlersMap: TypeAlias = dict[type[Exception], AiohttpExceptionHandler] |
| 33 | + |
| 34 | + |
| 35 | +def _sort_exceptions_by_specificity( |
| 36 | + exceptions: Iterable[type[Exception]], *, concrete_first: bool = True |
| 37 | +) -> list[type[Exception]]: |
| 38 | + """ |
| 39 | + Keyword Arguments: |
| 40 | + concrete_first -- If True, concrete subclasses precede their superclass (default: {True}). |
| 41 | + """ |
| 42 | + return sorted( |
| 43 | + exceptions, |
| 44 | + key=lambda exc: sum(issubclass(e, exc) for e in exceptions if e is not exc), |
| 45 | + reverse=not concrete_first, |
| 46 | + ) |
| 47 | + |
| 48 | + |
| 49 | +class ExceptionHandlingContextManager(AbstractAsyncContextManager): |
| 50 | + """ |
| 51 | + A dynamic try-except context manager for handling exceptions in web handlers. |
| 52 | + Maps exception types to corresponding handlers, allowing structured error management, i.e. |
| 53 | + essentially something like |
| 54 | + ``` |
| 55 | + try: |
| 56 | +
|
| 57 | + resp = await handler(request) |
| 58 | +
|
| 59 | + except exc_type1 as exc1: |
| 60 | + resp = await exc_handler1(request) |
| 61 | + except exc_type2 as exc1: |
| 62 | + resp = await exc_handler2(request) |
| 63 | + # etc |
| 64 | +
|
| 65 | + ``` |
| 66 | + and `exception_handlers_map` defines the mapping of exception types (`exc_type*`) to their handlers (`exc_handler*`). |
| 67 | + """ |
| 68 | + |
| 69 | + def __init__( |
| 70 | + self, |
| 71 | + exception_handlers_map: ExceptionHandlersMap, |
| 72 | + *, |
| 73 | + request: web.Request, |
| 74 | + ): |
| 75 | + self._exc_handlers_map = exception_handlers_map |
| 76 | + self._exc_types_by_specificity = _sort_exceptions_by_specificity( |
| 77 | + list(self._exc_handlers_map.keys()), concrete_first=True |
| 78 | + ) |
| 79 | + self._request: web.Request = request |
| 80 | + self._response: web.StreamResponse | None = None |
| 81 | + |
| 82 | + def _get_exc_handler_or_none( |
| 83 | + self, exc_type: type[Exception], exc_value: Exception |
| 84 | + ) -> AiohttpExceptionHandler | None: |
| 85 | + exc_handler = self._exc_handlers_map.get(exc_type) |
| 86 | + if not exc_handler and ( |
| 87 | + base_exc_type := next( |
| 88 | + ( |
| 89 | + _type |
| 90 | + for _type in self._exc_types_by_specificity |
| 91 | + if isinstance(exc_value, _type) |
| 92 | + ), |
| 93 | + None, |
| 94 | + ) |
| 95 | + ): |
| 96 | + exc_handler = self._exc_handlers_map[base_exc_type] |
| 97 | + return exc_handler |
| 98 | + |
| 99 | + async def __aenter__(self): |
| 100 | + self._response = None |
| 101 | + return self |
| 102 | + |
| 103 | + async def __aexit__( |
| 104 | + self, |
| 105 | + exc_type: type[BaseException] | None, |
| 106 | + exc_value: BaseException | None, |
| 107 | + traceback: TracebackType | None, |
| 108 | + ) -> bool: |
| 109 | + if ( |
| 110 | + exc_value is not None |
| 111 | + and exc_type is not None |
| 112 | + and isinstance(exc_value, Exception) |
| 113 | + and issubclass(exc_type, Exception) |
| 114 | + and (exc_handler := self._get_exc_handler_or_none(exc_type, exc_value)) |
| 115 | + ): |
| 116 | + self._response = await exc_handler( |
| 117 | + request=self._request, exception=exc_value |
| 118 | + ) |
| 119 | + return True # suppress |
| 120 | + return False # reraise |
| 121 | + |
| 122 | + def get_response_or_none(self) -> web.StreamResponse | None: |
| 123 | + """ |
| 124 | + Returns the response generated by the exception handler, if an exception was handled. Otherwise None |
| 125 | + """ |
| 126 | + return self._response |
| 127 | + |
| 128 | + |
| 129 | +def exception_handling_decorator( |
| 130 | + exception_handlers_map: dict[type[Exception], AiohttpExceptionHandler] |
| 131 | +) -> Callable[[WebHandler], WebHandler]: |
| 132 | + """Creates a decorator to manage exceptions raised in a given route handler. |
| 133 | + Ensures consistent exception management across decorated handlers. |
| 134 | +
|
| 135 | + SEE examples test_exception_handling |
| 136 | + """ |
| 137 | + |
| 138 | + def _decorator(handler: WebHandler): |
| 139 | + @functools.wraps(handler) |
| 140 | + async def _wrapper(request: web.Request) -> web.StreamResponse: |
| 141 | + cm = ExceptionHandlingContextManager( |
| 142 | + exception_handlers_map, request=request |
| 143 | + ) |
| 144 | + async with cm: |
| 145 | + return await handler(request) |
| 146 | + |
| 147 | + # If an exception was handled, return the exception handler's return value |
| 148 | + response = cm.get_response_or_none() |
| 149 | + assert response is not None # nosec |
| 150 | + return response |
| 151 | + |
| 152 | + return _wrapper |
| 153 | + |
| 154 | + return _decorator |
| 155 | + |
| 156 | + |
| 157 | +def exception_handling_middleware( |
| 158 | + exception_handlers_map: dict[type[Exception], AiohttpExceptionHandler] |
| 159 | +) -> WebMiddleware: |
| 160 | + """Constructs middleware to handle exceptions raised across app routes |
| 161 | +
|
| 162 | + SEE examples test_exception_handling |
| 163 | + """ |
| 164 | + _handle_excs = exception_handling_decorator( |
| 165 | + exception_handlers_map=exception_handlers_map |
| 166 | + ) |
| 167 | + |
| 168 | + @web.middleware |
| 169 | + async def middleware_handler(request: web.Request, handler: WebHandler): |
| 170 | + return await _handle_excs(handler)(request) |
| 171 | + |
| 172 | + return middleware_handler |
0 commit comments