Repository navigation
fix(web): show the message the API actually sends on an error - #30
Conversation
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — the full diff at 76f60a1 (3 files), plus independent verification of the two claims the fix rests on: eden's fetcher contract and the API's real error wire format.
errorMessagenow reads the body as text and parses optimistically —fromBodytriesJSON.parseand falls back to the raw text, takingmessagethenvalue.messageon an object;readable()gates out empty bodies, HTML pages and anything over 200 chars, sostatusText/GENERIC_ERRORbecome a true last resort rather than the normal path.- Network failures now surface — a custom
fetchertoasts and rethrows, leaving eden'sEdenFetchError(503)intact so call sites are unchanged;AbortErroris rethrown silently. - The test double mirrors the wire — raw
text/plainfor strings, JSON for objects, emptystatusText, plus afailToConnect()helper;api-client.spec.tsgoes from 7 to 16 cases.
Verified independently rather than taken on trust:
config.fetcheris real (@elysiajs/eden@1.4.9,dist/treaty2/types.d.ts:50) and there is exactly one call site indist/treaty2.js— the FormData upload path and GET-with-query both route through it. A fetcher rejectionreturns from inside eden'scatchbefore theonResponseloop, soonResponsegenuinely never runs and there is no double toast. The503is real, not assumed.- Every error shape
apps/apiemits was measured viaapp.handle. All thestatus(4xx/5xx, '<literal>')calls go out as raw text, validation errors as JSON with a shortmessage, and each maps to the intended toast under the new parser. No real message approaches the 200-char cap or starts with<. bun nx test web→ 77 passing in the sandbox.
The assertions in the new cases pin exact strings against behaviour that demonstrably differed before (the old .json() path yielded description: '' under the realistic mock), so the added coverage is real rather than decorative.
ℹ️ Faithfully relaying the API's text also relays its unhandled ones
The parser now shows whatever short, non-HTML string the API sends. That is the point of the PR, but it also means the API's unintentional strings reach the toast, where the old .json()-then-statusText path swallowed them. apps/api/src/app.ts has no root onError — only sessionModule defines one — so receiptModule and GET / serialize a raw error.message on an uncaught throw, and an unmatched route emits Elysia's bare NOT_FOUND token. Not reachable from the web client today, since nothing in apps/web/src calls /receipts through api, so this is a note for the API side rather than a change to make here.
Technical details
# Unhandled API errors would reach the user toast verbatim
## Affected sites
- `apps/api/src/app.ts:7-27` — root `Elysia` instance registers `cors`, `openapi`,
`sessionModule`, `receiptModule` and `GET /`, but no `onError`.
- `apps/api/src/modules/receipt/index.ts:12` — `receiptModule` defines no `onError`, so an
uncaught throw from `gcsReceiptStorage.get` is serialized as bare `error.message`
(measured: `GCS_BUCKET is not set`, status 500, no content-type).
- `apps/web/src/lib/api-client.ts:58-73` — `fromBody` returns any such string unchanged;
it is short, is not JSON and does not start with `<`, so `readable()` passes it through.
## Why it is not live
Nothing in `apps/web/src` requests `/receipts` through the eden client — receipt images are
not fetched via `api`. `sessionModule` has an `onError` that maps everything except
`VALIDATION` to `'Unexpected server error'`, which covers every route the web app calls.
## Required outcome
Decide whether the API should guarantee that no unhandled error text escapes, independent of
which module a future route lands in. A root `onError` on `apps/api/src/app.ts` mirroring the
`sessionModule` one would make that guarantee structural instead of per-module.
## Open questions for the human
- Is a follow-up on `apps/api` preferred over widening this PR?
- Should the raw `NOT_FOUND` token for an unmatched route be mapped to something friendlier,
or is it acceptable given the typed client makes an unmatched route near-impossible?ℹ️ Nitpicks
apps/web/src/lib/api-client.ts:38-39— theAbortErrorbranch and the test that covers it are unreachable today: a grep ofapps/web/srcfinds noAbortControllerorsignalforwarded to any call, and eden wraps an abort intoEdenFetchError(503)all the same. Worth keeping if request cancellation is planned, just noting it is currently defensive-only.
Claude Opus | 𝕏
There was a problem hiding this comment.
ℹ️ No new issues — the refactor is behaviour-preserving. One comment-loss nit inline.
Reviewed changes — the delta since the prior review at 76f60a1: one commit, a5cf520, touching only apps/web/src/lib/api-client.ts (29 insertions, 33 deletions). The tests and the mock are unchanged.
- Flattened the fallback chain —
fromBody()is gone and its logic is inlined intoerrorMessage(), which now parses the text and returns a single expression:readable(message) ?? readable(value?.message) ?? readable(body) ?? readable(statusText) ?? GENERIC_ERROR. - Inverted the
AbortErrorbranch infetcher()— the earlythrowbecame a negated guard aroundreport(NETWORK_ERROR), leaving onethrow errorat the end. - Condensed
readable()from an if/return into a ternary, and moved both helpers belowerrorMessage().
Traced both implementations side by side across every body shape — raw text, JSON string scalars, numbers, booleans, the literal null, arrays, objects with and without message, nested value.message, unreadable strings (empty, leading <, 201 chars), and an empty body — and found no divergence:
readable(body)is the merged replacement for the old code's two early returns (fromBody's catch branch and itstypeof body !== 'object'branch), not an extra chance to match. It cannot double-fire, becausebodyis an object exactly whenmessage/valueare in play, andreadable()returnsnullfor non-strings.(body ?? {})is load-bearing for exactly one input,JSON.parse('null'); without it the destructuring throws. Old and new both end atstatusText/GENERIC_ERRORthere.- The
readable()ternary readstext && … ? text : null, where the&&chain yields''for an empty body — falsy as a condition, so thenullbranch is still taken. Thelength === 200boundary stays inclusive.
bun nx test web → 77 passing (16 in api-client.spec.ts), bun nx lint web clean; the 6 remaining warnings are pre-existing noExplicitAny in apps/web/src/lib/react-query.ts, untouched here.
Claude Opus | 𝕏
`errorMessage` parsed every error body as JSON, but the API answers with a bare `text/plain` string on all of them (`status(404, 'Line item not found')` and friends). `JSON.parse` threw on each one and the code fell back to `response.statusText`, so the user saw the generic HTTP reason phrase — "Not Found" instead of "Line item not found". Worse, `statusText` is empty by specification over HTTP/2, so behind any proxy the toast rendered with no description at all. Report the body verbatim instead. The client has no business rewriting what the API says: no JSON unwrapping, no length limit, no HTML filter and no generic fallback. A validation failure now shows its whole JSON payload, which is the honest thing to show and stays rare — the forms validate with zod before a request goes out. Network failures were silent too: eden converts a rejected fetch into a 503 before `onResponse` ever runs, so no toast fired. That one does need handling. Wrap `fetcher` to report it and rethrow, leaving eden's `EdenFetchError(503)` intact for call sites. Aborted requests stay silent, since the browser cancels in-flight requests on navigation and that is not worth showing. The test mock hid all of this: it JSON-stringified every body, so `serve(403, 'Forbidden')` sent `"Forbidden"` quoted, which parsed cleanly. It now mirrors the wire — raw text/plain for strings, JSON for objects, empty `statusText` — and grows a `failToConnect` helper for the network case.
a5cf520 to
97009c5
Compare
There was a problem hiding this comment.
ℹ️ No critical issues. One user-visible regression against
mainon the JSON path, and the PR description no longer matches the code.
Reviewed changes — the delta since the prior review at a5cf520. The branch was force-pushed into a single commit, 97009c5, which deletes the parser the last two reviews traced and replaces it with a verbatim body passthrough.
errorMessage()is gone — along withreadable(),MAX_MESSAGE_LENGTHandGENERIC_ERROR.onResponsenow doesreport(await response.clone().text()): whatever bytes the server sent become the toast description, with no parsing, no shape check and no length cap.- Three tests were rewritten to assert the verbatim body — the proxy HTML page, the validation object and
{message:'Something broke'}now expect the raw text /JSON.stringifyoutput. Theit.eachfallback table and the nestedvalue.messagecase were dropped;api-client.spec.tsgoes from 16 cases to 12. fetcher,report()andrespond.tsare unchanged froma5cf520.
For the shape that dominates real traffic this is the right call and a clear win: every error the API actually defines is a bare text/plain literal ('Unauthorized', 'Line item not found', 'Session is not editable', 'Receipt analysis failed', 'Unexpected server error' — verified in apps/api/src/plugins/auth.ts and apps/api/src/modules/session/), JSON.parse threw on every one of them under main, and statusText is empty over HTTP/2. bun nx test web → 73 passing in the sandbox.
ℹ️ The PR description documents an implementation that is no longer in the branch
The body describes errorMessage() parsing optimistically, a readable gate that "drops empty bodies, a proxy's HTML error page and anything too long to be a sentence", and statusText as a last resort. None of that exists at 97009c5 — the gate was deleted and the HTML page is now shown deliberately, with a test asserting it. The Verification block also claims 422 -> "Expected required property" and 77 passing (api-client went from 7 to 16 cases); the actual figures are 73 and 12, and a 422 now renders the whole JSON object. Since this is a squashed single-commit PR, the body is the record that survives the merge.
Technical details
# PR description describes the deleted parser, not the merged code
## Affected sites
- PR #30 body, "Changes" section — describes `errorMessage()` reading the body as
text and parsing optimistically, "JSON only wins when it carries a `message`",
and a `readable` gate dropping empty bodies, HTML pages and over-long strings.
`apps/web/src/lib/api-client.ts:24` is now `report(await response.clone().text())`;
`errorMessage`, `readable`, `MAX_MESSAGE_LENGTH` and `GENERIC_ERROR` no longer exist.
- PR #30 body, "Verification" table — claims `422 -> "Expected required property"`.
`apps/web/src/lib/__test__/api-client.spec.ts:102` now asserts the toast shows
`JSON.stringify(body)` for that same input.
- PR #30 body, "Verification" — claims `bun nx test web` → 77 passing, api-client
7 → 16 cases. Measured at `97009c5`: 73 passing, 12 cases in `api-client.spec.ts`.
- PR #30 body, "Deliberately out of scope" — "422 still surfaces TypeBox internals
rather than a friendly message" understates the current behaviour: it surfaces the
entire TypeBox object, not its `message`.
## Required outcome
The description should describe the passthrough that is actually merging, so the
squashed commit message and the PR record match the code. If dropping the
`readable`/length guards was a deliberate simplification, saying so explicitly is
worth more than the deleted prose — it tells the next reader the raw-body behaviour
is a choice rather than an oversight.ℹ️ Nitpicks
apps/web/src/lib/__test__/api-client.spec.ts:79-88— "reports a proxy error page as it comes" pins the full HTML page as the toast description, andToastDescription(libs/shadcn-ui/src/toast.tsx:81-92) renders it as a plain text child with no length cap (ToastContenthasoverflow-hidden, nomax-height). No XSS risk, and it is not a regression —mainproduced an empty toast here. Just noting that a real gateway page is kilobytes rather than the 37 characters in the fixture, so the rendered result is likely to differ a lot from what the test suggests.
Claude Opus | 𝕏

The bug
onResponsefires correctly — the broken part iserrorMessage(), which assumed everyerror body is JSON. The API never sends JSON for business errors. Measured against a live
Elysia server over HTTP:
text/plain;charset=utf-8Line item not found(raw, unquoted).json()throws →statusText→ "Not Found"application/json{type,on,property,message,…}message(TypeBox internals)So none of the messages the API defines with care (
'Line item not found','Session is not editable','Receipt analysis failed') ever reached the user — they werereplaced by the generic HTTP reason phrase. And since
Response.statusTextis empty byspecification over HTTP/2, behind any proxy or CDN the toast rendered with an empty
description.
Why the tests did not catch it
apps/web/src/testing/respond.tsJSON-stringified every body withcontent-type: application/json, soserve(403, 'Forbidden')sent"Forbidden"quoted,which parses fine. The suite was green against a format the API never emits.
The mock now mirrors the wire (raw
text/plainfor strings, JSON for objects, emptystatusText). With the realistic mock but the old parser, two of the seven existingtests fail with
description: ''— the production bug, reproduced in CI.Changes
errorMessage()reads the body as text and parses optimistically: JSON only wins whenit carries a
message, otherwise the raw text is the message. Areadablegate dropsempty bodies, a proxy's HTML error page and anything too long to be a sentence, so
statusTextand a generic string are the last resort rather than the normal path.fetchinto a 503 beforeonResponseruns, so nothing was shown at all.fetcheris wrapped to toast and rethrow,leaving Eden's
EdenFetchError(503)intact — call sites are unchanged. Aborted requestsstay silent, since the browser cancels in-flight requests on navigation.
failToConnecthelper.Call sites are untouched: every one still does
if (error) throw apiError(error.value, …).Verification
Verified against a live Elysia server over real HTTP, using the same literals the API returns:
bun nx test web→ 77 passing (api-client went from 7 to 16 cases),biome lintandbiome formatclean on the three touched files.New cases cover: the plain-text literal, an empty body, a proxy HTML error page, a JSON
object with no
message, an over-long body, a nestedvalue.message, a validation failure,a network failure (asserting status 503 and the toast) and an aborted request (asserting
silence).
bun nx tsc:typecheck webis blocked by a pre-existing workspace sync error (stalelibs/shared-typesproject references inapps/api/tsconfig.jsonandapps/web/tsconfig.app.json). Confirmed it fails identically on a pristinemainwith thesechanges stashed, so it is unrelated and left alone rather than dragged into this PR.
Deliberately out of scope
text/plainstrings; no JSON error envelope.toast, and dialogs stay open.