Skip to content

fix(web): show the message the API actually sends on an error - #30

Merged
aek676 merged 1 commit into
mainfrom
fix/api-error-messages
Aug 11, 2026
Merged

aek676 merged 1 commit into
mainfrom
fix/api-error-messages

Conversation

@aek676

@aek676 aek676 commented Aug 11, 2026

Copy link
Copy Markdown
Owner

The bug

onResponse fires correctly — the broken part is errorMessage(), which assumed every
error body is JSON. The API never sends JSON for business errors. Measured against a live
Elysia server over HTTP:

Case Content-Type Body What the user saw
401 / 403 / 404 / 409 / 500 / 502 text/plain;charset=utf-8 Line item not found (raw, unquoted) .json() throws → statusText → "Not Found"
422 validation 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 were
replaced by the generic HTTP reason phrase. And since Response.statusText is empty by
specification 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.ts JSON-stringified every body with
content-type: application/json, so serve(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/plain for strings, JSON for objects, empty
statusText). With the realistic mock but the old parser, two of the seven existing
tests fail
with description: '' — the production bug, reproduced in CI.

Changes

  • errorMessage() reads the body as text and parses optimistically: JSON only wins when
    it carries a message, otherwise the raw text is the message. A readable gate drops
    empty bodies, a proxy's HTML error page and anything too long to be a sentence, so
    statusText and a generic string are the last resort rather than the normal path.
  • Network failures now report. Eden turns a rejected fetch into a 503 before
    onResponse runs, so nothing was shown at all. fetcher is wrapped to toast and rethrow,
    leaving Eden's EdenFetchError(503) intact — call sites are unchanged. Aborted requests
    stay silent, since the browser cancels in-flight requests on navigation.
  • The mock reproduces the API's wire format, plus a failToConnect helper.

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:

401 -> "Unauthorized"              409 -> "Session is not editable"
403 -> "Forbidden"                 500 -> "Unexpected server error"
404 -> "Line item not found"       502 -> "Receipt analysis failed"
422 -> "Expected required property"

bun nx test web → 77 passing (api-client went from 7 to 16 cases), biome lint and
biome format clean 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 nested value.message, a validation failure,
a network failure (asserting status 503 and the toast) and an aborted request (asserting
silence).

bun nx tsc:typecheck web is blocked by a pre-existing workspace sync error (stale
libs/shared-types project references in apps/api/tsconfig.json and
apps/web/tsconfig.app.json). Confirmed it fails identically on a pristine main with these
changes stashed, so it is unrelated and left alone rather than dragged into this PR.

Deliberately out of scope

  • 422 still surfaces TypeBox internals rather than a friendly message.
  • The API keeps returning bare text/plain strings; no JSON error envelope.
  • No error boundary or inline mutation-error UI — a failed mutation still only produces a
    toast, and dialogs stay open.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ 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.

  • errorMessage now reads the body as text and parses optimistically — fromBody tries JSON.parse and falls back to the raw text, taking message then value.message on an object; readable() gates out empty bodies, HTML pages and anything over 200 chars, so statusText/GENERIC_ERROR become a true last resort rather than the normal path.
  • Network failures now surface — a custom fetcher toasts and rethrows, leaving eden's EdenFetchError(503) intact so call sites are unchanged; AbortError is rethrown silently.
  • The test double mirrors the wire — raw text/plain for strings, JSON for objects, empty statusText, plus a failToConnect() helper; api-client.spec.ts goes from 7 to 16 cases.

Verified independently rather than taken on trust:

  • config.fetcher is real (@elysiajs/eden@1.4.9, dist/treaty2/types.d.ts:50) and there is exactly one call site in dist/treaty2.js — the FormData upload path and GET-with-query both route through it. A fetcher rejection returns from inside eden's catch before the onResponse loop, so onResponse genuinely never runs and there is no double toast. The 503 is real, not assumed.
  • Every error shape apps/api emits was measured via app.handle. All the status(4xx/5xx, '<literal>') calls go out as raw text, validation errors as JSON with a short message, 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 — the AbortError branch and the test that covers it are unreachable today: a grep of apps/web/src finds no AbortController or signal forwarded to any call, and eden wraps an abort into EdenFetchError(503) all the same. Worth keeping if request cancellation is planned, just noting it is currently defensive-only.

Pullfrog  | View workflow run | Using Claude Opus | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ℹ️ 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 into errorMessage(), which now parses the text and returns a single expression: readable(message) ?? readable(value?.message) ?? readable(body) ?? readable(statusText) ?? GENERIC_ERROR.
  • Inverted the AbortError branch in fetcher() — the early throw became a negated guard around report(NETWORK_ERROR), leaving one throw error at the end.
  • Condensed readable() from an if/return into a ternary, and moved both helpers below errorMessage().

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 its typeof body !== 'object' branch), not an extra chance to match. It cannot double-fire, because body is an object exactly when message/value are in play, and readable() returns null for non-strings.
  • (body ?? {}) is load-bearing for exactly one input, JSON.parse('null'); without it the destructuring throws. Old and new both end at statusText/GENERIC_ERROR there.
  • The readable() ternary reads text && … ? text : null, where the && chain yields '' for an empty body — falsy as a condition, so the null branch is still taken. The length === 200 boundary 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Claude Opus | 𝕏

Comment thread apps/web/src/lib/api-client.ts Resolved
`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.
@aek676
aek676 force-pushed the fix/api-error-messages branch from a5cf520 to 97009c5 Compare August 11, 2026 10:41

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ℹ️ No critical issues. One user-visible regression against main on 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 with readable(), MAX_MESSAGE_LENGTH and GENERIC_ERROR. onResponse now does report(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.stringify output. The it.each fallback table and the nested value.message case were dropped; api-client.spec.ts goes from 16 cases to 12.
  • fetcher, report() and respond.ts are unchanged from a5cf520.

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, and ToastDescription (libs/shadcn-ui/src/toast.tsx:81-92) renders it as a plain text child with no length cap (ToastContent has overflow-hidden, no max-height). No XSS risk, and it is not a regression — main produced 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Claude Opus | 𝕏

Comment thread apps/web/src/lib/api-client.ts Resolved
@aek676
aek676 merged commit 466b5f8 into main Aug 11, 2026
2 checks passed
@aek676
aek676 deleted the fix/api-error-messages branch August 11, 2026 11:05
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.

1 participant