From fed3ef1e7a39728e3aa13fb829da44f7e40eccae Mon Sep 17 00:00:00 2001 From: Arijit Basu Date: Wed, 27 Dec 2023 15:02:33 +0530 Subject: [PATCH] Add errors.not_found_on_none helper Also display correct info when `using hug`. --- apphelpers/errors/__init__.py | 6 ++++-- apphelpers/errors/fastapi.py | 10 +++++++++- apphelpers/errors/hug.py | 10 ++++++++++ 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/apphelpers/errors/__init__.py b/apphelpers/errors/__init__.py index 6ab92cc..dccda63 100644 --- a/apphelpers/errors/__init__.py +++ b/apphelpers/errors/__init__.py @@ -1,6 +1,8 @@ try: - print("apphelpers: using FastAPI") from apphelpers.errors.fastapi import * # noqa: F401, F403 + + print("apphelpers: using FastAPI") except ImportError: - print("apphelpers: using hug") from apphelpers.errors.hug import * # noqa: F401, F403 + + print("apphelpers: using hug") diff --git a/apphelpers/errors/fastapi.py b/apphelpers/errors/fastapi.py index bb40b21..7656b75 100644 --- a/apphelpers/errors/fastapi.py +++ b/apphelpers/errors/fastapi.py @@ -1,8 +1,10 @@ from dataclasses import dataclass -from typing import ClassVar +from typing import ClassVar, Optional, TypeVar from fastapi import HTTPException, status +T = TypeVar("T") + @dataclass class BaseError(HTTPException): @@ -46,3 +48,9 @@ class HTTP409Conflict(BaseError): @dataclass class InvalidSessionError(HTTP401Unauthorized): detail: str = "Invalid Session" + + +def not_found_on_none(obj: Optional[T], detail: str = "Not Found") -> T: + if obj is None: + raise HTTP404NotFound(detail) + return obj diff --git a/apphelpers/errors/hug.py b/apphelpers/errors/hug.py index f49f7dd..1ff482a 100644 --- a/apphelpers/errors/hug.py +++ b/apphelpers/errors/hug.py @@ -1,5 +1,9 @@ +from typing import Optional, TypeVar + from falcon import HTTPError, status_codes +T = TypeVar("T") + class BaseError(HTTPError): # Whether to report this error to honeybadger @@ -44,3 +48,9 @@ class InvalidSessionError(BaseError): class ConflictError(BaseError): status = status_codes.HTTP_409 description = "Duplicate resource" + + +def not_found_on_none(obj: Optional[T], detail: str = "Not Found") -> T: + if obj is None: + raise NotFoundError(description=detail) + return obj