From 8997ab35a0b065a71542ac4fc6c4b6d4ef999dbe Mon Sep 17 00:00:00 2001
From: Pavel Kirilin <win10@list.ru>
Date: Thu, 2 May 2024 04:07:15 +0200
Subject: [PATCH] Fixed exception handling.

Signed-off-by: Pavel Kirilin <win10@list.ru>
---
 anime/__main__.py | 22 +++++++++-------------
 anime/routes.py   | 15 ++++++---------
 2 files changed, 15 insertions(+), 22 deletions(-)

diff --git a/anime/__main__.py b/anime/__main__.py
index a86fc03..a27812e 100644
--- a/anime/__main__.py
+++ b/anime/__main__.py
@@ -1,6 +1,7 @@
 from pathlib import Path
 from typing import Optional
 from fastapi import FastAPI, HTTPException, Request, Response
+from fastapi.responses import JSONResponse
 from fastapi.staticfiles import StaticFiles
 from typer import Typer, Argument
 import uvicorn
@@ -13,18 +14,13 @@ STATIC_DIR = CURRENT_DIR / "static"
 cli = Typer()
 
 
-async def response_formatter(request: Request, call_next):
-    try:
-        response = await call_next(request)
-        print(response)
-    except Exception as e:
-        response = Response(
-            status_code=500,
-            content={
-                "detail": str(e),
-            },
-        )
-    return response
+async def default_exception_handler(request, exc):
+    return JSONResponse(
+        {
+            "detail": str(exc),
+        },
+        status_code=500,
+    )
 
 
 @cli.command()
@@ -48,7 +44,7 @@ def run_app(
             check_dir=False,
         ),
     )
-    app.add_middleware(BaseHTTPMiddleware, dispatch=response_formatter)
+    app.add_exception_handler(Exception, default_exception_handler)
     app.state.anime_dir = anime_dir
     app.state.pid = None
 
diff --git a/anime/routes.py b/anime/routes.py
index 7c2a418..5492047 100644
--- a/anime/routes.py
+++ b/anime/routes.py
@@ -13,7 +13,7 @@ router = APIRouter()
 @router.get("/can-start-watching")
 def can_start_watching(request: Request) -> None:
     if not request.app.state.anime_dir:
-        raise HTTPException(status_code=400, detail="Anime directory is not set.")
+        raise HTTPException(status_code=400, detail="Anime directory is not set")
 
 
 @router.post("/kill")
@@ -26,7 +26,7 @@ def kill(input_dto: KillRequest) -> None:
 def start_watching(request: Request) -> None:
     anime_dir = request.app.state.anime_dir
     if not anime_dir:
-        raise HTTPException(status_code=400, detail="Anime directory is not set.")
+        raise HTTPException(status_code=400, detail="Anime directory is not set")
     if request.app.state.pid:
         try:
             os.kill(request.app.state.pid, 0)
@@ -35,14 +35,11 @@ def start_watching(request: Request) -> None:
         else:
             raise HTTPException(
                 status_code=400,
-                detail="Awatch is already running.",
+                detail="Awatch is already running",
             )
     awatch = shutil.which("awatch")
     if awatch is None:
-        raise Exception(
-            "awatch command is not available. Please install awatch.\n"
-            "https://gitlab.le-memese.com/s3rius/awatch/"
-        )
+        raise Exception("awatch command is not available")
     ret = subprocess.Popen(
         [awatch],
         cwd=anime_dir,
@@ -59,7 +56,7 @@ async def offset(req: PlayerOffsetRequest) -> None:
     if playerctl is None:
         raise HTTPException(
             status_code=500,
-            detail="playerctl command is not available.",
+            detail="playerctl command is not available",
         )
 
     subprocess.run(
@@ -74,7 +71,7 @@ async def play_pause() -> None:
     if playerctl is None:
         raise HTTPException(
             status_code=500,
-            detail="playerctl command is not available.",
+            detail="playerctl command is not available",
         )
 
     subprocess.run([playerctl, "play-pause"], check=False)
-- 
GitLab