Created
March 25, 2025 16:08
-
-
Save andreagrandi/e53110a70539e6acf6227adef3ffcf31 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 FastAPI, HTTPException | |
from fastapi.responses import JSONResponse | |
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}, | |
) | |
# FastAPI application | |
fastapi_app = FastAPI() | |
# Register exception handler for FastAPI | |
fastapi_app.add_exception_handler(HTTPException, http_exception_handler) | |
@fastapi_app.get("/foo") | |
def fastapi_endpoint(): | |
raise CustomHTTPException("FastAPI error occurred", error_code="fast_api_error") | |
client = TestClient(fastapi_app) | |
res = client.get("/foo") | |
print(res.json()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment