Why does the framework raise a 500 instead of a 400 #4656
-
|
I have this route that I am building with query parameters, but there is are difference services that will be invoked based on the query parameter selected. I have it functioning correctly, but when conflicting query parameters are used, the pydantic model raises a value error, but litestar returns a 500 instead of 400. for context, this is what the controller function looks like: @get(
operation_id="GetDataByQueryParameters",
path="/data",
media_type=MediaType.JSON,
status_code=status_codes.HTTP_200_OK,
dependencies={"filters": Provide(DataQuery, sync_to_thread=False)},
raises=[ValidationException],
)
async def get_data(
self,
data_service: DataService,
filters: DataQuery
) -> list[Data]:
if filters.has_user_id:
return await data_service.get_data(
user_id=filters.user_id,
)
else:
return await data_service.get_data_by_source(
source=filters.source
)The Pydantic model looks like this: class DataQuery(BaseModel):
source: Annotated[
str | None,
Parameter(description="Source", examples=[Example(value="500MNY")]),
] = None
user_id: Annotated[
str | None,
Parameter(description="User Id", examples=[Example(value="DS2943")]),
] = None
@property
def has_source(self) -> bool:
return self.source is not None
@property
def has_user_id(self) -> bool:
return self.user_id is not None
@model_validator(mode="after")
def validate_exclusivity(self) -> "DataQuery":
if self.has_source and self.has_user_id:
raise ValueError("Query Parameters cannot include both Source and User Id")
return self
@field_validator("user_id", mode="before")
@classmethod
def lower_case_user_id(cls, value:str ) -> str | None:
if isinstance(value, str):
return value.lower()
else:
return NoneMy issue is that the Value error is raised, but it is just mapped as 500, I would like to find a way to have it return a 400 Bad Request Error instead. Any help would be greatly appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Because the You can either raise |
Beta Was this translation helpful? Give feedback.
Because the
ValueErroris just a regular exception. Litestar doesn't know about it. How could Litestar infer that thisValueErrorhas to do with input data validation and should map to a400response?You can either raise
ValidationError, raise aClientErrordirectly, or create your own exception class and register an error handler for it.