Skip to content

Raising HTTPException vs returning Response #2227

Answered by provinzkraut
gsakkis asked this question in Q&A
Discussion options

You must be logged in to vote

In what case would you use the one or the other, or it's just a matter of style?

In this example, they are functionally equivalent. The difference is mainly control flow. You can easily raise an HTTPException somewhere deep within a nested call you made from your route handler, and it will immediately abort the request. To do this with a regular Response, you'd have to explicitly pass that as a return type up the chain.

Is it deliberate that Response knows how to serialize Pydantic models and HTTPException doesn't?

It is, yes. Exceptions are intentionally more "low level" than responses, simply to avoid complexity and a whole catalogue of potential exception cases within those excepti…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
0 replies
Answer selected by JacobCoffee
Comment options

You must be logged in to vote
2 replies
@provinzkraut
Comment options

@gsakkis
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
Enhancement This is a new feature or request Question This is a question and further information is requested
2 participants
Converted from issue

This discussion was converted from issue #2226 on August 26, 2023 08:45.