Encode exception details as json #9096
Replies: 4 comments
-
|
I'm also running into this and from the documentation I thought this was expected behaviour:
Using |
Beta Was this translation helpful? Give feedback.
-
|
I have used jsonable_encoder. from fastapi.encoders import jsonable_encoder print(jsonable_encoder(example)) |
Beta Was this translation helpful? Give feedback.
-
|
Both |
Beta Was this translation helpful? Give feedback.
-
|
Test: from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel
from datetime import date
class Example(BaseModel):
name: str
date: date
app = FastAPI()
@app.get("/")
async def index():
example = Example(name="example", date=date.today())
raise HTTPException(status_code=400, detail=example)
def test_():
client = TestClient(app)
resp = client.get("/") # Raises TypeError: Object of type Example is not JSON serializable
assert resp.status_code == 200 |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
I was working with FastApi and Pydantic when I noticed that passing a Pydantic model as detail to a HttpException causes another exception (if the model contains normally unjsonable fields such as datetime):
A simple example:
This would cause a
TypeError: Object of type Example is not JSON serializableThis could be easily fixed by changing
exception_handlers.py:Since it might be intentional, I've labelled the issue as a suggestion
P.S. calling json() on the model when raising the exception works too, but the result has ugly formatting and escape characters
Beta Was this translation helpful? Give feedback.
All reactions