Fixed exception handling.

Signed-off-by: Pavel Kirilin <win10@list.ru>
This commit is contained in:
2024-05-02 04:07:15 +02:00
parent 8559ec7a85
commit 8997ab35a0
2 changed files with 15 additions and 22 deletions

View File

@ -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),
async def default_exception_handler(request, exc):
return JSONResponse(
{
"detail": str(exc),
},
status_code=500,
)
return response
@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

View File

@ -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)