Skip to content

Commit

Permalink
refactor: add exception handler decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
moonlitgrace committed Sep 22, 2023
1 parent f3c34a8 commit b82667a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 12 deletions.
20 changes: 19 additions & 1 deletion app/api/decorators/return_decorator.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from fastapi import HTTPException
import functools
from collections.abc import Callable
from typing import Any, TypeVar
Expand All @@ -13,10 +14,27 @@ def decorator(func: Callable[..., Any]) -> Callable[..., T]:
def wrapper(*args: Any, **kwargs: Any) -> T:
try:
return func(*args, **kwargs)

except AttributeError:
return return_type

return wrapper

return decorator


def return_on_404():
def decorator(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
# propagates HTTPException from function
except HTTPException:
raise
# catches all other execptions
except Exception:
raise HTTPException(status_code=404, detail="Page not found")

return wrapper

return decorator
19 changes: 8 additions & 11 deletions app/api/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
# helpers
from .helpers.string import StringHelper

# decorators
from .decorators.return_decorator import return_on_404

# scrapers
from .scrapers.popular import PopularScraper
from .scrapers.topten import TopTenScraper
Expand Down Expand Up @@ -73,20 +76,14 @@ async def get_most_viewed(chart: str, offset: int = 0, limit: int = Query(10, le
summary="Manga",
description="Get more details about a specific Manga by `slug`, eg: `/manga/one-piece-3/` - returns the full details of that specific Manga.",
)
@return_on_404()
async def get_manga(slug: str):
try:
response = BaseMangaScraper(url=f"https://mangareader.to/{slug}").build_dict()

if not response["title"]:
raise HTTPException(
status_code=404, detail=f"Manga with slug {slug} was not found"
)
response = BaseMangaScraper(url=f"https://mangareader.to/{slug}").build_dict()

if not response["title"]:
raise HTTPException(status_code=404, detail=f"Manga with slug {slug} was not found")
else:
return response

except Exception as e:
# Handle other exceptions as well, such as network issues
raise HTTPException(status_code=404, detail=f"Page not found")


@router.get(
Expand Down

0 comments on commit b82667a

Please sign in to comment.