fastapi icon indicating copy to clipboard operation
fastapi copied to clipboard

add __str__ method to HTTPException

Open ebottos94 opened this issue 2 years ago • 6 comments

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 :

image

After my commit :

image

ebottos94 avatar Jan 12 '23 13:01 ebottos94

📝 Docs preview for commit 56b5ef49570c95d62005104545b0a7b07f2ba3c0 at: https://63c00a0c532d1a08e4b3b617--fastapi.netlify.app

github-actions[bot] avatar Jan 12 '23 13:01 github-actions[bot]

📝 Docs preview for commit faecd67131e43f6a2c3b3b1fe922c2a06aca77d5 at: https://63c091ea27c5670c98d75fc0--fastapi.netlify.app

github-actions[bot] avatar Jan 12 '23 23:01 github-actions[bot]

You should add tests to pass the coverage requirement.

Thank you @odiseo0, I've add test and change string representation as you suggested.

ebottos94 avatar Jan 12 '23 23:01 ebottos94

Does it make sense to add this Starlette itself?🤔 Just wondering

iudeen avatar Jan 13 '23 19:01 iudeen

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')")

Kyle-sandeman-mrdfood avatar Jun 09 '23 14:06 Kyle-sandeman-mrdfood

We'll implement this in Starlette.

Ref.: https://github.com/encode/starlette/pull/2181

Kludex avatar Jun 11 '23 17:06 Kludex

https://github.com/encode/starlette/pull/2181 was merged.

Kludex avatar Jul 18 '23 19:07 Kludex

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! ☕

tiangolo avatar Sep 27 '23 21:09 tiangolo