Raising HTTPException vs returning Response #2227
-
I'm trying to understand the difference between raising an from typing import Any
from litestar import Litestar, Response, get
from litestar.exceptions import HTTPException
from litestar.status_codes import HTTP_402_PAYMENT_REQUIRED
from pydantic import BaseModel
class Character(BaseModel):
name: str
nickname: str | None = None
the_dude = Character(name="Jeffrey Lebowski", nickname="The Dude")
@get("/response")
async def response(extra: bool = False) -> Response[dict[str, Any]]:
return Response(
status_code=HTTP_402_PAYMENT_REQUIRED,
content=dict(
status_code=HTTP_402_PAYMENT_REQUIRED,
detail="Where's the money, Lebowski?",
extra=the_dude if extra else {},
),
)
@get("/exception")
async def exception(extra: bool = False) -> None:
raise HTTPException(
status_code=HTTP_402_PAYMENT_REQUIRED,
detail="Where's the money, Lebowski?",
extra=the_dude if extra else {},
)
app = Litestar(route_handlers=[response, exception])
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
In this example, they are functionally equivalent. The difference is mainly control flow. You can easily raise an
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 exceptions. The closer exceptions come to regular responses, the more can go wrong with them. That being said, we could support this, but I'd argue that it should be opt-in, e.g. with a special |
Beta Was this translation helpful? Give feedback.
-
Well you mentioned a benefit of exceptions, aborting immediately the request instead of explicitly passing the response up the chain. This benefit stands regardless of whether A counterargument could be that you can serialize the |
Beta Was this translation helpful? Give feedback.
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 regularResponse
, you'd have to explicitly pass that as a return type up the chain.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…