Skip to content

Commit

Permalink
ValidationException.errors() are ErrorDetails
Browse files Browse the repository at this point in the history
Update the documentation to explain that `RequestValidationError` isn't
literally a subclass since Pydantic V2.
  • Loading branch information
tamird committed May 6, 2024
1 parent e04d397 commit 25da9fd
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 54 deletions.
2 changes: 1 addition & 1 deletion docs/en/docs/tutorial/handling-errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ path -> item_id
!!! warning
These are technical details that you might skip if it's not important for you now.

`RequestValidationError` is a sub-class of Pydantic's <a href="https://docs.pydantic.dev/latest/concepts/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>.
`RequestValidationError` is morally a sub-class of Pydantic's <a href="https://docs.pydantic.dev/latest/concepts/models/#error-handling" class="external-link" target="_blank">`ValidationError`</a>.

**FastAPI** uses it so that, if you use a Pydantic model in `response_model`, and your data has an error, you will see the error in your log.

Expand Down
40 changes: 9 additions & 31 deletions fastapi/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
Union,
)

from fastapi.exceptions import RequestErrorModel
from fastapi.exceptions import ErrorDetails, RequestErrorModel
from fastapi.types import IncEx, ModelNameMap, UnionType
from pydantic import BaseModel, create_model
from pydantic.version import VERSION as P_VERSION
Expand Down Expand Up @@ -121,7 +121,7 @@ def validate(
values: Dict[str, Any] = {}, # noqa: B006
*,
loc: Tuple[Union[int, str], ...] = (),
) -> Tuple[Any, Union[List[Dict[str, Any]], None]]:
) -> Tuple[Any, Union[List[ErrorDetails], None]]:
try:
return (
self._type_adapter.validate_python(value, from_attributes=True),
Expand Down Expand Up @@ -167,9 +167,6 @@ def get_annotation_from_field_info(
) -> Any:
return annotation

def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]:
return errors # type: ignore[return-value]

def _model_rebuild(model: Type[BaseModel]) -> None:
model.model_rebuild()

Expand Down Expand Up @@ -265,12 +262,12 @@ def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]:
assert issubclass(origin_type, sequence_types) # type: ignore[arg-type]
return sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return]

def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]:
def get_missing_field_error(loc: Tuple[str, ...]) -> ErrorDetails:
error = ValidationError.from_exception_data(
"Field required", [{"type": "missing", "loc": loc, "input": {}}]
).errors(include_url=False)[0]
error["input"] = None
return error # type: ignore[return-value]
return error

def create_body_model(
*, fields: Sequence[ModelField], model_name: str
Expand Down Expand Up @@ -418,20 +415,6 @@ def is_pv1_scalar_sequence_field(field: ModelField) -> bool:
return True
return False

def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]:
use_errors: List[Any] = []
for error in errors:
if isinstance(error, ErrorWrapper):
new_errors = ValidationError( # type: ignore[call-arg]
errors=[error], model=RequestErrorModel
).errors()
use_errors.extend(new_errors)
elif isinstance(error, list):
use_errors.extend(_normalize_errors(error))
else:
use_errors.append(error)
return use_errors

def _model_rebuild(model: Type[BaseModel]) -> None:
model.update_forward_refs()

Expand Down Expand Up @@ -500,10 +483,10 @@ def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo:
def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]:
return sequence_shape_to_type[field.shape](value) # type: ignore[no-any-return,attr-defined]

def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]:
def get_missing_field_error(loc: Tuple[str, ...]) -> ErrorDetails:
missing_field_error = ErrorWrapper(MissingError(), loc=loc) # type: ignore[call-arg]
new_error = ValidationError([missing_field_error], RequestErrorModel)
return new_error.errors()[0] # type: ignore[return-value]
return new_error.errors()[0]

def create_body_model(
*, fields: Sequence[ModelField], model_name: str
Expand All @@ -515,14 +498,9 @@ def create_body_model(


def _regenerate_error_with_loc(
*, errors: Sequence[Any], loc_prefix: Tuple[Union[str, int], ...]
) -> List[Dict[str, Any]]:
updated_loc_errors: List[Any] = [
{**err, "loc": loc_prefix + err.get("loc", ())}
for err in _normalize_errors(errors)
]

return updated_loc_errors
*, errors: Sequence[ErrorDetails], loc_prefix: Tuple[Union[str, int], ...]
) -> List[ErrorDetails]:
return [{**err, "loc": loc_prefix + err.get("loc", ())} for err in errors]


def _annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool:
Expand Down
7 changes: 4 additions & 3 deletions fastapi/dependencies/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
contextmanager_in_threadpool,
)
from fastapi.dependencies.models import Dependant, SecurityRequirement
from fastapi.exceptions import ErrorDetails
from fastapi.logger import logger
from fastapi.security.base import SecurityBase
from fastapi.security.oauth2 import OAuth2, SecurityScopes
Expand Down Expand Up @@ -654,7 +655,7 @@ def request_params_to_args(
received_params: Union[Mapping[str, Any], QueryParams, Headers],
) -> Tuple[Dict[str, Any], List[Any]]:
values = {}
errors = []
errors: list[ErrorDetails] = []
for field in required_params:
if is_scalar_sequence_field(field) and isinstance(
received_params, (QueryParams, Headers)
Expand Down Expand Up @@ -687,9 +688,9 @@ def request_params_to_args(
async def request_body_to_args(
required_params: List[ModelField],
received_body: Optional[Union[Dict[str, Any], FormData]],
) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:
) -> Tuple[Dict[str, Any], List[ErrorDetails]]:
values = {}
errors: List[Dict[str, Any]] = []
errors: List[ErrorDetails] = []
if required_params:
field = required_params[0]
field_info = field.field_info
Expand Down
25 changes: 19 additions & 6 deletions fastapi/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
from typing import Any, Dict, Optional, Sequence, Type, Union
from typing import Any, Dict, Optional, Sequence, Tuple, Type, Union

from pydantic import BaseModel, create_model
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.exceptions import WebSocketException as StarletteWebSocketException
from typing_extensions import Annotated, Doc
from typing_extensions import Annotated, Doc, TypedDict


class ErrorDetails(TypedDict):
"""
The common subset shared by `ErrorDict` in Pydantic V1[0] and `ErrorDetails` in Pydantic V2[1].
[0] https://github.com/pydantic/pydantic/blob/4d7bef62aeff10985fe67d13477fe666b13ba070/pydantic/v1/error_wrappers.py#L21-L22
[1] https://github.com/pydantic/pydantic-core/blob/e1fc99dd3207157aad77defc20ab6873fd268b5b/python/pydantic_core/__init__.py#L73-L91
"""

loc: Tuple[Union[int, str], ...]
msg: str
type: str


class HTTPException(StarletteHTTPException):
Expand Down Expand Up @@ -147,15 +160,15 @@ class FastAPIError(RuntimeError):


class ValidationException(Exception):
def __init__(self, errors: Sequence[Any]) -> None:
def __init__(self, errors: Sequence[ErrorDetails]) -> None:
self._errors = errors

def errors(self) -> Sequence[Any]:
def errors(self) -> Sequence[ErrorDetails]:
return self._errors


class RequestValidationError(ValidationException):
def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:
def __init__(self, errors: Sequence[ErrorDetails], *, body: Any = None) -> None:
super().__init__(errors)
self.body = body

Expand All @@ -165,7 +178,7 @@ class WebSocketRequestValidationError(ValidationException):


class ResponseValidationError(ValidationException):
def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:
def __init__(self, errors: Sequence[ErrorDetails], *, body: Any = None) -> None:
super().__init__(errors)
self.body = body

Expand Down
20 changes: 7 additions & 13 deletions fastapi/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
Undefined,
_get_model_config,
_model_dump,
_normalize_errors,
lenient_issubclass,
)
from fastapi.datastructures import Default, DefaultPlaceholder
Expand All @@ -39,6 +38,7 @@
)
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import (
ErrorDetails,
FastAPIError,
RequestValidationError,
ResponseValidationError,
Expand Down Expand Up @@ -132,7 +132,7 @@ async def serialize_response(
is_coroutine: bool = True,
) -> Any:
if field:
errors = []
errors: list[ErrorDetails] = []
if not hasattr(field, "serialize"):
# pydantic v1
response_content = _prepare_response_content(
Expand All @@ -147,14 +147,10 @@ async def serialize_response(
value, errors_ = await run_in_threadpool(
field.validate, response_content, {}, loc=("response",)
)
if isinstance(errors_, list):
if errors_ is not None:
errors.extend(errors_)
elif errors_:
errors.append(errors_)
if errors:
raise ResponseValidationError(
errors=_normalize_errors(errors), body=response_content
)
raise ResponseValidationError(errors=errors, body=response_content)

if hasattr(field, "serialize"):
return field.serialize(
Expand Down Expand Up @@ -251,7 +247,7 @@ async def app(request: Request) -> Response:
"msg": "JSON decode error",
"input": {},
"ctx": {"error": e.msg},
}
} # type: ignore [typeddict-unknown-key]
],
body=e.doc,
)
Expand Down Expand Up @@ -309,9 +305,7 @@ async def app(request: Request) -> Response:
response.body = b""
response.headers.raw.extend(sub_response.headers.raw)
if errors:
validation_error = RequestValidationError(
_normalize_errors(errors), body=body
)
validation_error = RequestValidationError(errors=errors, body=body)
raise validation_error
if response is None:
raise FastAPIError(
Expand Down Expand Up @@ -343,7 +337,7 @@ async def app(websocket: WebSocket) -> None:
)
values, errors, _, _2, _3 = solved_result
if errors:
raise WebSocketRequestValidationError(_normalize_errors(errors))
raise WebSocketRequestValidationError(errors)
assert dependant.call is not None, "dependant.call must be a function"
await dependant.call(**values)

Expand Down

0 comments on commit 25da9fd

Please sign in to comment.