fixing code related to exception handling

This commit is contained in:
maxDorninger
2025-06-24 18:44:49 +02:00
parent d0c26f3e6e
commit 8b4da3ba3d
2 changed files with 78 additions and 17 deletions

View File

@@ -1,16 +1,57 @@
class MediaAlreadyExists(ValueError): from fastapi import Request, HTTPException
from fastapi.responses import JSONResponse
class MediaAlreadyExists(Exception):
"""Raised when a show already exists""" """Raised when a show already exists"""
def __init__(
self, message: str = "Entity with this ID or other identifier already exists"
):
super().__init__(message)
self.message = message
pass pass
class NotFoundError(Exception): class NotFoundError(Exception):
"""Custom exception for when an entity is not found.""" """Custom exception for when an entity is not found."""
def __init__(self, message: str = "The requested entity was not found."):
super().__init__(message)
self.message = message
pass pass
class InvalidConfigError(Exception): class InvalidConfigError(Exception):
"""Custom exception for when an entity is not found.""" """Custom exception for when an entity is not found."""
def __init__(self, message: str = "The server is improperly configured."):
super().__init__(message)
self.message = message
pass pass
async def media_already_exists_exception_handler(
request: Request, exc: MediaAlreadyExists | Exception
) -> JSONResponse:
return JSONResponse(
status_code=401,
content={"detail": exc.message},
)
async def not_found_error_exception_handler(
request: Request, exc: NotFoundError | Exception
) -> JSONResponse:
return JSONResponse(
status_code=404,
content={"detail": exc.message},
)
async def invalid_config_error_exception_handler(
request: Request, exc: InvalidConfigError | Exception
) -> JSONResponse:
return JSONResponse(
status_code=500,
content={"detail": exc.message},
)

View File

@@ -3,10 +3,8 @@ import os
import sys import sys
from logging.config import dictConfig from logging.config import dictConfig
from pathlib import Path from pathlib import Path
from pythonjsonlogger.json import JsonFormatter from pythonjsonlogger.json import JsonFormatter
LOGGING_CONFIG = { LOGGING_CONFIG = {
"version": 1, "version": 1,
"disable_existing_loggers": False, "disable_existing_loggers": False,
@@ -48,21 +46,17 @@ logging.basicConfig(
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
from media_manager.database import init_db # noqa: E402 from media_manager.database import init_db # noqa: E402
from media_manager.config import BasicConfig # noqa: E402
import media_manager.tv.router as tv_router # noqa: E402
import media_manager.torrent.router as torrent_router # noqa: E402 import media_manager.torrent.router as torrent_router # noqa: E402
import media_manager.movies.router as movies_router # noqa: E402 import media_manager.movies.router as movies_router # noqa: E402
import media_manager.tv.router as tv_router # noqa: E402
from media_manager.tv.service import ( # noqa: E402 from media_manager.tv.service import ( # noqa: E402
auto_download_all_approved_season_requests, auto_download_all_approved_season_requests,
import_all_torrents, import_all_torrents,
update_all_non_ended_shows_metadata, update_all_non_ended_shows_metadata,
) )
from media_manager.config import BasicConfig # noqa: E402
import shutil # noqa: E402 import shutil # noqa: E402
from fastapi import FastAPI # noqa: E402 from fastapi import FastAPI # noqa: E402
from fastapi.middleware.cors import CORSMiddleware # noqa: E402 from fastapi.middleware.cors import CORSMiddleware # noqa: E402
from datetime import datetime # noqa: E402 from datetime import datetime # noqa: E402
@@ -143,9 +137,19 @@ from media_manager.auth.users import ( # noqa: E402
cookie_auth_backend, cookie_auth_backend,
openid_cookie_auth_backend, openid_cookie_auth_backend,
) )
from media_manager.exceptions import (
NotFoundError,
not_found_error_exception_handler,
MediaAlreadyExists,
media_already_exists_exception_handler,
InvalidConfigError,
invalid_config_error_exception_handler,
)
# ----------------------------
# Standard Auth Routers # Standard Auth Routers
# ----------------------------
app.include_router( app.include_router(
fastapi_users.get_auth_router(bearer_auth_backend), fastapi_users.get_auth_router(bearer_auth_backend),
prefix="/auth/jwt", prefix="/auth/jwt",
@@ -171,17 +175,24 @@ app.include_router(
prefix="/auth", prefix="/auth",
tags=["auth"], tags=["auth"],
) )
# All users route router
# ----------------------------
# User Management Routers
# ----------------------------
app.include_router(custom_users_router, tags=["users"]) app.include_router(custom_users_router, tags=["users"])
# OAuth Metadata Router
app.include_router(auth_metadata_router, tags=["openid"])
# User Router
app.include_router( app.include_router(
fastapi_users.get_users_router(UserRead, UserUpdate), fastapi_users.get_users_router(UserRead, UserUpdate),
prefix="/users", prefix="/users",
tags=["users"], tags=["users"],
) )
# OAuth2 Routers
# ----------------------------
# OpenID Connect Routers
# ----------------------------
app.include_router(auth_metadata_router, tags=["openid"])
if openid_client is not None: if openid_client is not None:
app.include_router( app.include_router(
get_oauth_router( get_oauth_router(
@@ -205,9 +216,18 @@ app.mount(
name="static-images", name="static-images",
) )
# ----------------------------
# Custom Exception Handlers
# ----------------------------
app.add_exception_handler(NotFoundError, not_found_error_exception_handler)
app.add_exception_handler(MediaAlreadyExists, media_already_exists_exception_handler)
app.add_exception_handler(InvalidConfigError, invalid_config_error_exception_handler)
log.info("Hello World!") log.info("Hello World!")
# ----------------------------
# Startup filesystem checks # Startup filesystem checks
# ----------------------------
try: try:
test_dir = basic_config.tv_directory / Path(".media_manager_test_dir") test_dir = basic_config.tv_directory / Path(".media_manager_test_dir")
test_dir.mkdir(parents=True, exist_ok=True) test_dir.mkdir(parents=True, exist_ok=True)