From 3b9bbd38d961e4acb1b23614df75b87f71e91a7f Mon Sep 17 00:00:00 2001 From: fjt <18513358973@163.com> Date: Wed, 15 Apr 2026 22:56:16 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E5=BC=82=E5=B8=B8=E5=A4=84=E7=90=86):=20?= =?UTF-8?q?=E6=94=B9=E8=BF=9B=E9=AA=8C=E8=AF=81=E9=94=99=E8=AF=AF=E7=9A=84?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E5=8C=96=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 _format_error 方法以更清晰地展示验证错误的详细信息,包括位置、类型、消息和输入值。当存在多个错误时,会为每个错误添加编号以提升可读性。 --- fastapi/exceptions.py | 44 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/fastapi/exceptions.py b/fastapi/exceptions.py index d7065c52fe..6c2571e2f3 100644 --- a/fastapi/exceptions.py +++ b/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()