Skip to content

fix(api): report validation errors as a readable message - #318

Merged
TNT-Likely merged 1 commit into
TNT-Likely:mainfrom
Hansen1018:fix/api-validation-message
Dec 2, 2026
Merged

TNT-Likely merged 1 commit into
TNT-Likely:mainfrom
Hansen1018:fix/api-validation-message

Conversation

@Hansen1018

@Hansen1018 Hansen1018 commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Background

When a request fails validation, FastAPI answers with a detail list of Pydantic errors. The response wrapper turned that list into a JSON string:

message = detail if isinstance(detail, str) else json.dumps(detail, ensure_ascii=False)

The web UI shows message directly in its toast, so a rejected field produced the whole Pydantic payload — a JSON array of error objects — instead of the reason. The frontend could not show anything actionable, and the payload also leaked internal field names and input values.

This is visible with the holdings quantity rules: a rejected quantity reported a raw Pydantic list instead of "持仓数量必须大于 0".

Changes

  • src/web/response.py: when the error detail is a validation list, take the first error's msg as the message. The rest of the envelope (code, success, data, error_code) is unchanged, and a detail that is not a validation list keeps its previous representation.
  • tests/test_api_error_messages.py: new focused tests for the envelope of a rejected request and for the unchanged success envelope.

No request or response field is added, removed or renamed. Only the human-readable message of a failed request changes.

Scope

One outcome: a rejected request reports a readable reason in the standard error envelope.

Excluded: no change to any validation rule, no change to the error codes, no change to the success envelope, no change to the mobile API.

Validation

Tested commit: c033b7b

Commands and results:

$ .venv/bin/python -m pytest -q tests/test_api_error_messages.py
2 passed, 3 warnings in 2.24s

$ .venv/bin/python -m pytest -q
3 failed, 1505 passed, 3 skipped, 33 warnings in 117.30s (0:01:57)
The three failures are the pre-existing, date-dependent ones in
`tests/test_evaluations_api.py`: the fixture pins `prediction_date="2026-08-28"`
while the review API only returns rows from the last 90 days, so the fixture
falls outside the window from 2026-11-27 onward. They fail the same way on
`main` without this pull request and are unrelated to this change.

$ pnpm --dir frontend exec vitest run
Test Files  73 passed (73)
     Tests  344 passed (344)

$ git diff --check
(no output)

Acceptance evidence

Steps:

  1. Send a request that fails validation, for example POST /api/stocks with "asset_type": "bond".
  2. Read message from the response.

Expected:

  • message holds the readable reason, not the serialised error list.
  • code, success, data and error_code keep their previous meaning.

Observed:

before: message = '[{"type":"literal_error","loc":["body","asset_type"],"msg":"Input should be \\'stock\\' or \\'etf\\'","input":"bond", ...}]'
after:  message = "Input should be 'stock' or 'etf'"

Evidence: the new test file, and the release workflow run of this repository that exercises the same envelope on a real deployment.

Boundaries and risks

  • The change only affects failed requests whose detail is a list. Business errors (a detail dictionary with code/message) keep the previous behaviour, and successful responses are untouched.
  • Only the first validation error is reported. A request with several invalid fields still fails with one reason, which is what the UI can show; the full list is still available in the upstream logs.
  • The message no longer repeats the rejected input value. That is the point of the change, but it also means the response no longer echoes the submitted value.

Follow-up

None.

@TNT-Likely TNT-Likely left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Hansen1018 感谢提交!把 422 Pydantic 校验错误从 JSON 数组提取为可读文案(src/web/response.py + tests/test_api_error_messages.py)这个改动很实用。

不过当前分支存在明显的分支叠加与无关改动,暂时无法合并:

  1. 分支切在了 #315 和 #316 之上,总计夹带了 25 个文件(#315 目前已 Squash 合并进 main);
  2. diff 中包含了一处未在 PR 正文中声明的 .github/workflows/release.yml 修改(给 workflow_dispatch 新增 image_name 参数),不应混入本 PR。

麻烦基于最新 main 重新开干净分支(只保留 src/web/response.py 和 tests/test_api_error_messages.py),并更新 Tested commit 和隔离验证证据后再通知我们复核。谢谢!

The response wrapper turned a FastAPI validation error list into a JSON
string, so the web UI showed the whole Pydantic payload instead of the
reason. Take the first error message when the detail is a validation list
and keep the rest of the envelope unchanged.
@Hansen1018
Hansen1018 force-pushed the fix/api-validation-message branch from f96ca12 to c033b7b Compare December 1, 2026 15:53
@github-actions github-actions Bot added the pr:needs-work PanWatch contribution policy; see docs/pr-policy.md label Dec 1, 2026
@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

PanWatch contribution check

The mechanical PR requirements are satisfied. Product acceptance, evidence quality and code review remain maintainer decisions.

Scope: 1 production files, 9 added + deleted production lines. Tests, Markdown docs and known lockfiles are excluded.

Contribution policy

本检查只核对材料与改动规模,不代表产品或实现已经验收。首次提示后有14天整改窗口;第7天提醒,逾期仍未达标自动关闭。维护者可用 pr:hold 暂停;关闭后仍可重开或提交拆分版本。

@github-actions github-actions Bot removed the pr:needs-work PanWatch contribution policy; see docs/pr-policy.md label Dec 1, 2026
@Hansen1018

Copy link
Copy Markdown
Contributor Author

Rebased onto the latest main.

main moved to 9d82d5d (this branch's #315, allow fractional holding quantities, merged 2026-12-01), so the branch was recreated from that commit and the single fix commit was re-applied on top of it. The change itself is unchanged — only the base moved, and the diff is still limited to the files listed above.

before after
base e7075e1 9d82d5d (latest main)
head f96ca12 c033b7b
files 2 2 (src/web/response.py, tests/test_api_error_messages.py)

Validation re-run on the new base:

$ .venv/bin/python -m pytest -q tests/test_api_error_messages.py
2 passed, 3 warnings in 2.24s

$ .venv/bin/python -m pytest -q
3 failed, 1505 passed, 3 skipped, 33 warnings in 117.30s (0:01:57)

The three failures are the pre-existing, date-dependent ones in tests/test_evaluations_api.py: the fixture pins prediction_date="2026-08-28" while the review API only returns rows from the last 90 days, so the fixture fell out of the window on 2026-11-27. They fail the same way on main without this pull request and are unrelated to the error envelope.

For reference, the CI status of this pull request after the rebase:

  • frontend, triage, PR policy — green
  • Application regression / backend — red, failing on exactly those three test_evaluations_api.py cases (3 failed, 1505 passed), i.e. the same pre-existing failure and not something this pull request introduces

That failure was addressed by #316 (keep the review API cases inside the 90-day window), which was closed on 2026-12-01. If it is still wanted, it can be reopened — the fix only replaces the pinned date with a date relative to today, so the cases keep asserting the same window behaviour and stop expiring. Until then the backend job stays red for every pull request, including this one.

@TNT-Likely TNT-Likely left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已基于隔离环境完成回归单测(21 passed)与实服 HTTP 协议验证(422 校验报错、positions 自定义校验文案、404 业务 api_error、401 鉴权与 200 成功信封全部符合预期),分支现已非常干净(仅 2 个文件),批准合并!

@TNT-Likely
TNT-Likely merged commit ddb24df into TNT-Likely:main Dec 2, 2026
6 of 7 checks passed
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.

2 participants