From bdc648970464bff4fd4f983dc15c649193fa0a57 Mon Sep 17 00:00:00 2001 From: Noam Stolero Date: Tue, 19 Nov 2024 18:03:21 +0200 Subject: [PATCH] feat(litestar): add default NotFoundError exception handler Add a default exception handler for NotFoundError in the SQLAlchemyPlugin. The handler returns a standardized 404 response with JSON content. The handler is automatically registered if no other handler for NotFoundError is configured. Signed-off-by: Noam Stolero --- .../extensions/litestar/plugins/__init__.py | 6 ++++++ .../extensions/litestar/plugins/exception_handlers.py | 11 +++++++++++ 2 files changed, 17 insertions(+) create mode 100644 advanced_alchemy/extensions/litestar/plugins/exception_handlers.py diff --git a/advanced_alchemy/extensions/litestar/plugins/__init__.py b/advanced_alchemy/extensions/litestar/plugins/__init__.py index 6a2df208..af2804f7 100644 --- a/advanced_alchemy/extensions/litestar/plugins/__init__.py +++ b/advanced_alchemy/extensions/litestar/plugins/__init__.py @@ -4,7 +4,9 @@ from litestar.plugins import InitPluginProtocol +from advanced_alchemy.exceptions import NotFoundError from advanced_alchemy.extensions.litestar.plugins import _slots_base +from advanced_alchemy.extensions.litestar.plugins.exception_handlers import not_found_error_handler from advanced_alchemy.extensions.litestar.plugins.init import ( EngineConfig, SQLAlchemyAsyncConfig, @@ -44,6 +46,10 @@ def on_app_init(self, app_config: AppConfig) -> AppConfig: app_config: The :class:`AppConfig <.config.app.AppConfig>` instance. """ app_config.plugins.extend([SQLAlchemyInitPlugin(config=self._config), SQLAlchemySerializationPlugin()]) + + if not app_config.exception_handlers.get(NotFoundError): + app_config.exception_handlers[NotFoundError] = not_found_error_handler + return app_config diff --git a/advanced_alchemy/extensions/litestar/plugins/exception_handlers.py b/advanced_alchemy/extensions/litestar/plugins/exception_handlers.py new file mode 100644 index 00000000..e16252af --- /dev/null +++ b/advanced_alchemy/extensions/litestar/plugins/exception_handlers.py @@ -0,0 +1,11 @@ +from litestar import MediaType, Request, Response + +from advanced_alchemy.exceptions import NotFoundError + + +def not_found_error_handler(_request: Request, _exc: NotFoundError) -> Response: + return Response( + media_type=MediaType.JSON, + content={"detail": "Not Found", "status_code": 404}, + status_code=404, + )