"""RFC 9457 problem responses. Hidden objects use the same 404 as missing ones.""" from __future__ import annotations from fastapi import Request from fastapi.responses import JSONResponse class Problem(Exception): def __init__(self, status: int, title: str, detail: str, code: str) -> None: super().__init__(detail) self.status = status self.title = title self.detail = detail self.code = code def body(self, instance: str) -> dict: return { "type": "about:blank", "title": self.title, "status": self.status, "detail": self.detail, "instance": instance, "code": self.code, } def unauthorized() -> Problem: return Problem(401, "Anmeldung erforderlich", "Die Sitzung fehlt oder ist abgelaufen.", "unauthorized") def forbidden(detail: str = "Diese Aktion ist im gewählten Kontext nicht erlaubt.") -> Problem: return Problem(403, "Keine Berechtigung", detail, "forbidden") def not_found() -> Problem: return Problem(404, "Nicht gefunden", "Der Eintrag ist nicht vorhanden.", "not_found") def conflict() -> Problem: return Problem( 409, "Versionskonflikt", "Der Stand hat sich geändert. Bitte neu laden.", "conflict", ) def unprocessable(detail: str) -> Problem: return Problem(422, "Eingabe ungültig", detail, "unprocessable") def too_many() -> Problem: return Problem(429, "Zu viele Versuche", "Bitte kurz warten und es erneut versuchen.", "too_many_requests") def storage_unavailable() -> Problem: return Problem( 503, "Speicher nicht verfügbar", "Die Datei kann gerade nicht gelesen oder geschrieben werden.", "storage_unavailable", ) def problem_response(problem: Problem, request: Request) -> JSONResponse: return JSONResponse( status_code=problem.status, content=problem.body(request.url.path), media_type="application/problem+json", )