I'm trying to understand the difference between raising an HTTPException vs returning a Response. Consider the following example:
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])
GET /response and GET /exception return the same status and body. In what case would you use the one or the other, or it's just a matter of style?
GET /response?extra=1 works, GET /exception?extra=1 raises SerializationException: Unsupported type: <class 'foo.Character'>. Is it deliberate that Response knows how to serialize Pydantic models and HTTPException doesn't? If yes why? If not I'd suggest this as a feature request.
I'm trying to understand the difference between raising an
HTTPExceptionvs returning aResponse. Consider the following example:GET /responseandGET /exceptionreturn the same status and body. In what case would you use the one or the other, or it's just a matter of style?GET /response?extra=1works,GET /exception?extra=1raisesSerializationException: Unsupported type: <class 'foo.Character'>. Is it deliberate thatResponseknows how to serialize Pydantic models and HTTPException doesn't? If yes why? If not I'd suggest this as a feature request.