Skip to content

Raising HTTPException vs returning Response #2226

@gsakkis

Description

@gsakkis

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])
  1. 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?
  2. 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    EnhancementThis is a new feature or requestQuestionThis is a question and further information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions