Skip to content

feat(web-api): единый контракт ошибок и HTTP-статусов - #583

Open
Ibochkarev wants to merge 5 commits into
betafrom
feat/issue-572-web-api-error-contract
Open

feat(web-api): единый контракт ошибок и HTTP-статусов#583
Ibochkarev wants to merge 5 commits into
betafrom
feat/issue-572-web-api-error-contract

Conversation

@Ibochkarev

Copy link
Copy Markdown
Member

Описание

Единый success/error envelope Web API /api/v1 для TypeScript/Nuxt: HTTP status больше не теряется через ->getData(), field errors живут в top-level errors, additive error_code (snake_case).

Envelope #341 сохранён. Nested { error: {…} } не вводим.

Ключевые изменения

  • ApiErrorCode + Response::error / errorWithCode / fromProcessor с error_code
  • Web-контроллеры возвращают Response (create address → HTTP 201)
  • Profile validation → top-level errors + HTTP 422 + зеркало data.errors (BC)
  • Address conflict: existing_id в data; list → {items, total}
  • Orders list: additive items (= orders)
  • Cart/Order: DomainMs2Response поднимает field map в errors/422, _nf → 404, иначе business_rule
  • Token/RateLimit middleware: token_expired / token_invalid / rate_limited; mint fail → 500/internal_error

Тип изменений

  • Новая функциональность (non-breaking change)
  • Breaking change (частично: addresses list shape, conflict payload path, HTTP 201/404/422 точнее)

Связанные Issues

Closes #572

Как это было протестировано?

cd core/components/minishop3
composer ci:php   # exit 0
composer stan     # exit 0
php tests/WebApiErrorContractTest.php
php tests/ResponseFromProcessorTest.php
  • Автоматические тесты (composer ci:php, composer stan)
  • Ручное тестирование против live MODX

Конфигурация тестирования:

  • MiniShop3: branch feat/issue-572-web-api-error-contract
  • PHP: 8.4

Чеклист

  • Код соответствует стилю проекта
  • PHPStan проходит без новых ошибок
  • Лексиконы не требовались (machine codes + существующие ключи)
  • CHANGELOG.md — на релизе (по политике репо)

Wire contract (кратко)

Ситуация HTTP error_code
validation fields 422 validation_failed
auth / token 401 unauthorized / token_*
not found 404 not_found
conflict 409 conflict
rate limit 429 rate_limited
cart/order domain 400 business_rule
mint token fail 500 internal_error

Success: { success, message, data } — без изменений ключей.

Дополнительные заметки

Сохраняем envelope #341 и добавляем machine error_code, чтобы Nuxt
получал стабильные 401/404/422/429 и field errors без getData()-потери status.
@Ibochkarev Ibochkarev added priority: medium Средний приоритет enhancement New feature or request labels Aug 16, 2026
Intelephense читал `@return Response ['…']` как array и ругался на Response::error.
@Ibochkarev
Ibochkarev requested a review from biz87 August 16, 2026 09:12
Имя error() совпадало с Response::error и давало ложный Expected array в IDE.
Убирает ложный Expected array у return Response::error в IDE.
Убирает transformResponse в OrderController, из‑за которого IDE видела return array.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request priority: medium Средний приоритет

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Web API: единый контракт ошибок и HTTP-статусов для TypeScript/Nuxt

1 participant