Browse Source

feat(异常处理): 改进验证错误的格式化输出

添加 _format_error 方法以更清晰地展示验证错误的详细信息,包括位置、类型、消息和输入值。当存在多个错误时,会为每个错误添加编号以提升可读性。
pull/15354/head
fjt 3 months ago
parent
commit
3b9bbd38d9
  1. 44
      fastapi/exceptions.py

44
fastapi/exceptions.py

@ -201,10 +201,50 @@ class ValidationException(Exception):
context += f"\n {self.endpoint_path}"
return context
def _format_error(self, err: Any) -> str:
if not isinstance(err, dict):
return f" {err}"
loc = err.get("loc")
msg = err.get("msg")
error_type = err.get("type")
has_input = "input" in err
input_val = err.get("input")
parts = []
if loc:
if isinstance(loc, (list, tuple)):
loc_str = " -> ".join(str(item) for item in loc)
else:
loc_str = str(loc)
parts.append(f" Loc: {loc_str}")
if error_type:
parts.append(f" Type: {error_type}")
if msg:
parts.append(f" Msg: {msg}")
if has_input:
input_str = str(input_val)
if len(input_str) > 50:
input_str = input_str[:47] + "..."
parts.append(f" Input: {input_str}")
if not parts:
return f" {err}"
return "\n".join(parts)
def __str__(self) -> str:
message = f"{len(self._errors)} validation error{'s' if len(self._errors) != 1 else ''}:\n"
for err in self._errors:
message += f" {err}\n"
for i, err in enumerate(self._errors):
if len(self._errors) > 1:
message += f"\nError {i + 1}:\n"
message += self._format_error(err)
if i < len(self._errors) - 1:
message += "\n"
message += self._format_endpoint_context()
return message.rstrip()

Loading…
Cancel
Save