Skip to content

Conversation

fraser-langton
Copy link

[DRAFT]

Initial pass at #1507 - just to show it is possible, and rather easy

from ninja import NinjaAPI, Schema
from ninja.errors import HttpError
from ninja.responses import codes_2xx

api = NinjaAPI()


class RequestErrorResponse(Schema):
    detail: str
    reason: list[str]


class ServerErrorResponse(Schema):
    detail: str


class BasicHttpError(HttpError): ...


class RequestError(HttpError[RequestErrorResponse]):
    status_code = 400
    message = "Request Error"


class ServerError(HttpError[ServerErrorResponse]):
    status_code = 500
    message = "Server Error"


@api.get(
    "/excs_in_responses",
    response={codes_2xx: str, 400: RequestError, 404: BasicHttpError, 500: ServerError},
)
def excs_in_responses(request): ...

The main concern I can think of if the disconnect between an exception and the response from the exception (which is done by the exception handler). I think this could be improved by making the HttpException class generate the Response in a method - either by making it a pydnatic model (this might be messy when combined with exception) or continuing with my implementation to use the Schema as a TypeVar (similar to pydantic Generic)

class HttpErrorResponse(BaseModel):
    detail: str


T = TypeVar("T", bound=HttpErrorResponse)


class HttpError(Exception, Generic[T]):
    __response_schema__ = HttpErrorResponse

    @property
    def response(self) -> T:
        return self.__response_schema__(detail=self.message)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant