ReviewOS

stacks/stx

useQuery/useMutation/useFetch throw before reading the body, so the server's error message is unreachable — the reason an app keeps 23 raw fetch() calls

#1848
Closed glennmichael123 opened this 22 days ago · 2 comments
22 days ago

Every data primitive throws on a non-2xx before reading the response body, so the server's own error message is unreachable. An app that wants to show "That email is already a member" instead of "HTTP 422: Unprocessable Entity" cannot use useQuery, useMutation or useFetch at all.

This is not a nitpick about error text. It is, as far as I can tell, the single reason a real app on stx kept 23 hand-written fetch() calls through a deliberate campaign to remove vanilla JS.

The code

packages/stx/src/signals.ts:1325 (useMutation):

var response = await __stxFetch('useMutation', resolvedUrl, fetchOpts);
if (!response.ok) throw new Error('HTTP ' + response.status + ': ' + response.statusText);
var result = await response.json();          // <- never reached on failure

The same shape, same order, in all four implementations:

signals.ts:1245useQuery
signals.ts:971-973useFetch (runtime)
composables/use-fetch.ts:211-212useFetch (module)

The error signal then carries only that synthesized string — error.set(e.message \|\| 'Query failed') (signals.ts:1256).

There is no escape hatch. options.transform runs only on the success path (signals.ts:1247, :1327), so it cannot see a failure body either.

Why it forces a retreat to raw fetch

An app that needs the server's message has to write this, every time:

const res = await fetch(url, { method: 'POST', body })
const data = await res.json().catch(() => ({}))
if (!res.ok) { error.set(data.error || 'Something went wrong.'); return }

Which is precisely what the app I measured does at 8 call sites — settings.stx:243-247 (rotate key), :446-450 (add channel), projects/new.stx:49-53, login.stx:51-54, AutofixPanel.stx:202-203, :228-229, :254-255. Every one reads the body first solely to reach data.error.

Adopting useMutation would silently downgrade every one of those messages. That is a product regression, so the primitive is unusable for mutations that can fail meaningfully — which is all of them.

What peers do

  • ofetch / Nuxt — FetchError.data carries the parsed body, so error.value.data.message works.
  • React Query — mutationFn is your own function; you parse and throw whatever you like.
  • Axios — error.response.data.
  • SWR — you supply the fetcher, same as React Query.

All four treat "the body of a failed response" as the primary error payload. stx discards it.

Suggested direction

Attach the body to the thrown error rather than changing the throw/no-throw contract:

if (!response.ok) {
  const body = await response.json().catch(() => undefined)
  const err = new Error('HTTP ' + response.status + ': ' + response.statusText)
  err.status = response.status
  err.data = body                     // <- the part that is missing
  throw err
}

error() would keep returning the same string it does today, so nothing breaks, and error().data?.error becomes reachable. Worth applying to all four implementations at once, since they are copies of each other.

Two adjacent notes:

  • Stacks already ships a helper shaped for exactly this — describeResponseError(status, body) at @stacksjs/browser/dist/composables/request-error.d.ts:1-12, whose doc comment describes this pattern. It is not in STX_RUNTIME_GLOBALS, so a client script cannot reach it.
  • A text/plain or empty body should degrade to today's behaviour rather than throw inside the error path.
22 days ago

Confirmed — bench (a real ~6.5k-line app) keeps 12 raw fetch() calls for exactly this reason: it needs the server's JSON error body (field validation messages, the anti-enumeration auth responses) which is unreachable when useFetch/useQuery throw before reading it.

The auth store wraps them in _apiFetch (resources/stores/auth.ts:132) specifically so it can read res.json() on a non-2xx and surface the message. Representative sites: stores/admin.ts:48, stores/subscribe.ts:24, stores/auth.ts:214/246, plus the form views (resources/views/contact.stx, forgot-password.stx, reset-password.stx). If useFetch exposed the response body on error, all of these collapse straight to it.

22 days ago

Fixed in 765b168.

All four sites now read the body before throwing, and carry it on the error:

HTTP 422: Unprocessable - Email already taken
  err.status  422
  err.data    { message: "Email already taken", errors: { email: ["taken"] } }

Attaching the body matters more than interpolating it — err.data is what a form needs to render per-field errors, and err.status is what a caller needs to tell 401 from 500 without parsing English. Both JSON shapes you'd expect are picked up (message and error), plus plain text, and an empty body still yields a sane HTTP 503: Unavailable.

Your framing was the useful part of this report: the problem isn't a missing primitive, it's that the primitive discards the one thing the caller needs. That's why an app keeps 23 raw fetch() calls even after adopting the framework.

Two implementation notes:

  • The three runtime sites were three copies of the same two lines, so they now go through one helper — and there's a test asserting no hand-built HTTP ' + response.status throw remains in the generated runtime, since three copies is how this drifts back.
  • The module use-fetch.ts twin is updated in the same commit for CLAUDE.md item-40 parity. Fixing only the runtime would have left the two impls disagreeing about error shape, which is its own bug.

This also closes the same ask filed inside #1855 (ask 3) and #1856 (ask 4) — worth noting on those when they're picked up, since the interceptor and form work no longer needs to carry it.

Full suite 10833 pass in a clean worktree.

Sign in to comment on this issue.