From b82667ab7807ea949130698c03a49ec6245ef233 Mon Sep 17 00:00:00 2001 From: tokitou-san Date: Fri, 22 Sep 2023 21:13:27 +0530 Subject: [PATCH] refactor: add exception handler decorator --- app/api/decorators/return_decorator.py | 20 +++++++++++++++++++- app/api/endpoints.py | 19 ++++++++----------- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/app/api/decorators/return_decorator.py b/app/api/decorators/return_decorator.py index e22a5f1..7e2b30f 100644 --- a/app/api/decorators/return_decorator.py +++ b/app/api/decorators/return_decorator.py @@ -1,3 +1,4 @@ +from fastapi import HTTPException import functools from collections.abc import Callable from typing import Any, TypeVar @@ -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 diff --git a/app/api/endpoints.py b/app/api/endpoints.py index 2b0761b..c0e60ac 100644 --- a/app/api/endpoints.py +++ b/app/api/endpoints.py @@ -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 @@ -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(