Skip to content

Commit

Permalink
Add errors.not_found_on_none helper
Browse files Browse the repository at this point in the history
Also display correct info when `using hug`.
  • Loading branch information
sayanarijit committed Dec 27, 2023
1 parent c3d6ff9 commit fed3ef1
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
6 changes: 4 additions & 2 deletions apphelpers/errors/__init__.py
Original file line number Diff line number Diff line change
@@ -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")
10 changes: 9 additions & 1 deletion apphelpers/errors/fastapi.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down Expand Up @@ -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
10 changes: 10 additions & 0 deletions apphelpers/errors/hug.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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

0 comments on commit fed3ef1

Please sign in to comment.