fastapi
fastapi copied to clipboard
add __str__ method to HTTPException
As mentioned in Iusse #5878 there's a bug in HTTPException's string representation, it seems that _repr_ method in starlette.exceptions.HTTPException doesn't works correctly without explicit call _repr_ method. To avoid this I've implemented a _str_ method in fastapi.exceptions.HTTPException
Current situation :
After my commit :
📝 Docs preview for commit 56b5ef49570c95d62005104545b0a7b07f2ba3c0 at: https://63c00a0c532d1a08e4b3b617--fastapi.netlify.app
📝 Docs preview for commit faecd67131e43f6a2c3b3b1fe922c2a06aca77d5 at: https://63c091ea27c5670c98d75fc0--fastapi.netlify.app
You should add tests to pass the coverage requirement.
Thank you @odiseo0, I've add test and change string representation as you suggested.
Does it make sense to add this Starlette itself?🤔 Just wondering
Honestly you could just do __str__ = __repr__
(in definition, not patched like below)
>>> from fastapi.exceptions import HTTPException
>>> h = HTTPException(status_code=200)
>>> str(h), repr(h)
('', "HTTPException(status_code=200, detail='OK')")
>>> HTTPException.__str__ = HTTPException.__repr__
>>> str(h), repr(h)
("HTTPException(status_code=200, detail='OK')", "HTTPException(status_code=200, detail='OK')")
>>> class Custom(HTTPException):
... pass
...
>>> c = Custom(status_code=201)
>>> str(c), repr(c)
("Custom(status_code=201, detail='Created')", "Custom(status_code=201, detail='Created')")
We'll implement this in Starlette.
Ref.: https://github.com/encode/starlette/pull/2181
https://github.com/encode/starlette/pull/2181 was merged.
Thanks @ebottos94! 🍰
And thanks everyone for the discussion. As @Kludex points out, as this is now in Starlette, I'll close this one here. But thanks for the effort! ☕