Created
March 25, 2025 16:08
-
-
Save andreagrandi/debbd116a078202aed59a6abc2e78c3d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fastapi import HTTPException | |
from fastapi.responses import JSONResponse | |
from cadwyn import Cadwyn, HeadVersion, Version, VersionBundle, VersionedAPIRouter | |
from fastapi.testclient import TestClient | |
GENERIC_ERROR_CODE = "generic_error" | |
class CustomHTTPException(HTTPException): | |
error_code: str | None = None | |
def __init__(self, detail: str, error_code: str = None): | |
self.error_code = error_code | |
super().__init__(status_code=400, detail=detail) | |
def http_exception_handler(request, exc): | |
# Check if the exception has an error_code attribute | |
error_code = exc.error_code if hasattr(exc, "error_code") else GENERIC_ERROR_CODE | |
return JSONResponse( | |
status_code=exc.status_code, | |
content={"code": error_code, "message": exc.detail}, | |
) | |
# Cadwyn application | |
versions = VersionBundle(HeadVersion(), Version("2025-03-25")) | |
cadwyn_app = Cadwyn(versions=versions) | |
# Register exception handler for Cadwyn | |
cadwyn_app.add_exception_handler(HTTPException, http_exception_handler) | |
versioned_router = VersionedAPIRouter() | |
@versioned_router.get("/foo") | |
def cadwyn_endpoint(): | |
raise CustomHTTPException("Cadwyn error occurred", error_code="cadwyn_error") | |
cadwyn_app.generate_and_include_versioned_routers(versioned_router) | |
client = TestClient(cadwyn_app) | |
res = client.get("/foo", headers={"x-api-version": "2025-03-25"}) | |
print(res.json()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment