Skip to content

fix(api): map a Postgres 22P02 cast failure to 400, on Payload's routes and in geojson - #685

Merged
sydevs-bot merged 3 commits into
mainfrom
claude/fix-22p02-cast-400
Sep 3, 2026
Merged

sydevs-bot merged 3 commits into
mainfrom
claude/fix-22p02-cast-400

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • A value Postgres cannot cast now returns 400 naming the offending value, not an unhandled 500. Covers both live instances — enum_meditations_type: "path" (Sentry 126185460) and integer: "NaN" (136881789).
  • Generic over SQLSTATE 22P02, not over enums, so within its reach it covers every enum, id and date cast that exists or is added later. Zero cost on a healthy request: it runs only after a query has already failed.
  • Sentry stops reporting them, so 300-odd "the server broke" events leave a channel where a 500 should mean wake someone.

⚠ Two seams, not one — the second was found by review. Payload's root afterError hook is invoked by routeError, which serves Payload's own REST routes. A custom endpoint that catches its own errors never reaches it, so GET /api/events/geojson — which forwards the client's where verbatim onto eventType, an enum column the OpenAPI docs advertise filtering on — was still answering a flat 500. It now calls the same predicate directly.

Changes

  • src/lib/databaseErrors/index.ts — the pure recogniser. Matches the SQLSTATE down the cause chain, since drizzle wraps every failed query.
  • src/plugins/databaseErrors/ — the afterError hook that answers with it and logs at WARN, for Payload's own REST routes.
  • src/collections/Events/endpoints/geojson.ts — the same mapping in a handler the hook cannot reach.
  • src/plugins/sentry/sentryPlugin.ts — asks the same predicate before reporting.
  • src/payload.config.ts, docs/architecture.md — registration, the behaviour written down, and what the seam does not reach.

Preview

The SahajCloud-pr-685 environment deployed successfully (logs) on the previous head; the new commit redeploys it.

⚠ No public host to link. Railway's comment leaves the Web column empty for this deploy, and scripts/get-railway-preview-url.ts needs RAILWAY_API_TOKEN, which this session does not hold — so the URL is neither published nor discoverable from here. The Manual verification commands below are written against $URL; the environment link above is where to get it.

Nothing here is reachable from a normal route anyway — the change is only observable through a deliberately-bad request.

Test results

  • Lean gate: ✓ lint, typecheck, typecheck:tests, test:unit (120 files / 1553 specs), all exit 0
  • Targeted: ✓ tests/unit/postgres-cast-error.spec.ts (12), ✓ tests/int/database-cast-errors.int.spec.ts (3), ✓ tests/int/events-geojson.int.spec.ts (23) — the last two against a real Postgres
  • CI: green on fcfb8f3; re-running on cfbab29
  • Build: N/A — Railway builds on the preview deploy

Manual verification

Against the preview, with an API key:

  1. curl -s -o /dev/null -w '%{http_code}' "$URL/api/meditations?where\[type\]\[equals\]=path&select\[id\]=true" → 400
  2. Same with equals=lesson → 200
  3. curl -s "$URL/api/lectures/daily_fallback_shri_mataji_clip" → 400, not 500
  4. curl -s "$URL/api/events/geojson?select\[title\]=true&depth=1&where\[eventType\]\[equals\]=bogus" → 400 with code: "22P02", not 500
  5. After deploy, Sentry 126185460 and 136881789 should record no new events.

Notes for reviewer

The ticket's two ⚠ unverified premises are measured, not assumed. Both were the reason it said "verify before implementing":

  1. afterError's return value does re-shape the REST response in [email protected] — routeError.js:82-85 assigns response = result.response || response and status = result.status || status before Response.json.
  2. The SQLSTATE does survive drizzle's wrapping, on cause. tests/int/database-cast-errors.int.spec.ts makes a real Postgres reject a real query and asserts it, so a drizzle or pg upgrade that stopped preserving cause reddens the lane instead of silently restoring the 500s.

Your Path/lesson call is recorded in the code, not just in the ticket — lesson is the in-code name for a Path step, sending the label is the client's mistake, and the 400 now says so.

One thing this PR trips over and does not fix, filed as #684: src/payload.config.ts:54 sets debug: true unconditionally, which switches off Payload's production error redaction — so today production already returns the full Failed query: … plus a stack trace for every unhandled error. This change narrows that for 22P02 (one Postgres message, no SQL, no parameters, no stack), but the general leak is wider than this ticket and belongs in its own PR.

One thread is deliberately left open — the consider on whether the Sentry suppression should discriminate on req.user. I declined it with evidence rather than silently; the decision is yours to reverse and the reasoning is in docs/architecture.md.

Design, what review changed, and the negative proofs

Why map the error rather than validate the query

Agreed on the ticket, and it holds up: the database is already making this judgement correctly and precisely at the moment it matters. A where-value check reaches only the 51 select fields, so it fixes the enum instance and leaves the integer one firing; and it re-derives per request, per field type, what one handler covers for everything.

The cost is message quality — Postgres names the type (enum_meditations_type), not the field, and cannot enumerate valid options. Shipped as the floor, as the ticket proposed: a blunt 400 that cannot miss a case beats a 500.

Why Sentry asks the predicate rather than reading a flag

captureErrors includes 400, so restatusing alone would keep reporting these — the noise would survive the fix. The Sentry hook therefore calls the same pure mapPostgresCastError. Asking rather than reading a marker the other hook sets means the order the two plugins are registered in is not load-bearing, which is one less invariant nothing checks.

What the adversarial review changed

Five findings. Two should-fix and two consider adopted; one consider rebutted.

  • The coverage claim was wider than the seam reaches, and geojson.ts was the concrete gap — a documented client route, forwarding the client's where onto an enum column, still answering 500 with no offending value named and no Sentry event. It calls mapPostgresCastError in its own catch now, and docs/architecture.md states the reach plus the obligation any future self-catching handler inherits. tests/int/events-geojson.int.spec.ts pins it against a real Postgres — watched failing at the site that causes it (expected 500 to be 400 with the catch reverted), then restored.
  • name: 'BadRequest' is gone. It was outside the published ErrorResponse schema and carried nothing the status did not. Replaced with code: '22P02', which is in that schema and is the one thing a client cannot recover by parsing Postgres prose.
  • postgresCastError.ts folded into lib/databaseErrors/index.ts — identical import path, no call site or spec touched, one file holding the idea instead of a header, a barrel and a plugin barrel each restating it.
  • The rationale is told once. The module header went from ~70 lines to ~20; the ⚠ block that narrated a review round is one imperative naming the spec that pins it; both plugin comments lost the paragraphs they repeated verbatim. docs/architecture.md carries the story.
  • Rebutted: discriminating the Sentry suppression on req.user. It would change nothing. hasPermission returns false for a null user (plugins/access/permissions.ts:59) and no collection overrides read publicly, so an anonymous read is denied before any SQL runs — req.user is set on every error that can reach these hooks, including a 22P02 our own code composes during a client's request, which is the case it was meant to catch. A job's own query never reaches the hook at all (routeError is the only invoker). And the signal it was meant to preserve already exists: routeError calls logError at ERROR with the full stack before any hook runs, so these are absent from Sentry but never invisible.

The earlier author-side review

Three findings, all acted on; a fourth was raised as a defect and then disproved by the security pass (it is #684's, above).

  • findPostgresError stopped at the first error carrying any string code, then compared — identical to matching the code only while nothing between Payload and the driver sets a code of its own, which is an assumption about somebody else's library rather than an invariant. Now it keeps walking, with an ECONNRESET decoy case that was watched failing against the old shape.
  • The WARN is additive, and the docs implied otherwise. routeError calls logError at ERROR with the full stack before any afterError hook runs, and loggingLevels cannot reach this error — it keys on err.name, which DrizzleQueryError never sets. Both lines are emitted; only the Sentry report goes.
  • The predicate cannot tell whose bad value it was. Stated as the accepted cost rather than left implied by "a genuine 500 stays a 500".

Measured while implementing, and worth knowing

payload.findByID({ collection: 'lectures', id: 'daily_fallback_shri_mataji_clip' }) throws Payload's own NotFound (404) before any SQL runs — the slug is not the way in through the local API. Only the numeric NaN reaches Postgres, which is what the integration spec asserts; the coercion in front of it belongs to the REST layer this lane cannot drive.

Closes #670

🤖 Written by the sydevs autonomous loop — see what this is


🤖 Generated with Claude Code

https://claude.ai/code/session_01BG2uTcLbYEjqrx62vc7yAS

A caller-supplied value Postgres cannot cast to a column's type raises
SQLSTATE 22P02 and reached the client as an unhandled 500. Two instances
are live in production and are the same error class one type apart:
`invalid input value for enum enum_meditations_type: "path"` (Sentry
126185460, 190 events since June) and `invalid input syntax for type
integer: "NaN"` (Sentry 136881789, 114 events).

This is a diagnosability problem, not a load one. A 500 tells the caller
nothing, which is why the first has fired unchanged for three months —
and 300-odd events of "the server broke" are noise in a channel where a
500 is supposed to mean wake someone.

Map the database error rather than pre-validating the query, per the
approach agreed on #670. The database is already making this judgement
correctly and precisely at the moment it matters; a `where`-value check
would only reach the 51 `select` fields, so it would fix the enum
instance and leave the integer one firing, and it would re-derive per
request what one handler covers for every enum, id and date cast that
exists or is added later. It also costs nothing on a healthy request,
because it runs only after a query has already failed.

Two things the ticket flagged as unverified, now measured rather than
assumed:

  - `afterError`'s return value does re-shape the REST response in
    [email protected] — `payload/dist/utilities/routeError.js` assigns
    `response = result.response` and `status = result.status` before
    `Response.json(response, { status })`.
  - the SQLSTATE does survive drizzle's wrapping, on `cause`.
    `tests/int/database-cast-errors.int.spec.ts` makes a real Postgres
    reject a real query and asserts it, so a drizzle or pg upgrade that
    stopped preserving `cause` reddens the lane instead of silently
    restoring the 500s.

The Sentry plugin asks the same pure predicate before reporting, rather
than reading a flag the other hook sets, so the two are independent of
the order they are registered in. Without that guard the noise would
survive the fix: `captureErrors` includes 400, so restatusing alone
would keep reporting them. Everything else is untouched — a genuine 500
stays a 500 and is still reported.

The `Path`/`lesson` mismatch behind the enum instance is recorded as
decided, not left open: `lesson` is the in-code name for a Path step and
sending the label is the client's mistake, which the 400 now says.

Both new assertions were watched failing at the site that would really
cause them — `findPostgresError` not walking `cause` — and restored:
3 unit and 2 integration assertions went red.

Closes #670

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PmKbZaa1XnbTvLehjR3GoG
Review found `findPostgresError` stopping at the first error carrying
*any* string `code`, then comparing. Those are the same thing only while
nothing between Payload and the driver sets a `code` of its own — true
of drizzle-orm 0.45.2, and an assumption about somebody else's library
rather than an invariant.

The failure it invites is silent and self-concealing: one wrapper with a
`code` (a Node `SystemError`, a future `DrizzleQueryError` revision) and
the 22P02 beneath it is never reached, so the request reverts to the 500
this change exists to remove *and* the Sentry suppression stops — with
both specs still green, because each pinned the chain at
drizzle-wrapper-over-pg-error. `findPostgresError` now takes the code to
look for and keeps walking; a new unit case puts an `ECONNRESET` decoy
between the wrapper and the driver, and was watched failing against the
old shape.

Two wording corrections from the same review, no behaviour change:

  - the WARN is **additive**. `routeError` calls `logError` at ERROR with
    the full stack before any `afterError` hook runs, and `loggingLevels`
    cannot reach it — that keys on `err.name`, which `DrizzleQueryError`
    never sets. Both lines are emitted; only the Sentry report goes.
    Anything alerting on ERROR still fires, and the docs implied it would
    not.
  - the predicate keys on the SQLSTATE alone, so a 22P02 **our own** code
    causes is now a 400 blaming the caller and is reported nowhere. That
    is the accepted cost of the trade, and it was worth stating where
    "a genuine 500 stays a 500" could be read as covering it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PmKbZaa1XnbTvLehjR3GoG
@sydevs-bot
sydevs-bot requested a review from Ardnived September 3, 2026 12:33
@railway-app

railway-app Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-685 environment in sahajcloud

Service Status Web Updated
SahajCloud ✅ Success (View Logs) Sep 3, 2026 at 2:16 pm UTC
1 service not affected by this PR
  • mailpit

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-685 September 3, 2026 12:33 Destroyed
@sydevs-bot
sydevs-bot marked this pull request as ready for review September 3, 2026 13:02

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

🧐 Adversarial review

The diff is the size of the ticket: ~60 lines of logic, ~240 of tests, ~150 of docs and comments, no refactor smuggled alongside. Both premises #670 flagged as unverified are genuinely settled, and I re-checked the first one independently against [email protected]'s dist/utilities/routeError.js — a hook's { response, status } is applied (response = result.response || response), hooks are reduced in registration order, and a later hook returning undefined does not clobber an earlier result, so the Sentry hook's early return is safe and the two plugins really are order-independent.

One shape problem is worth fixing before merge: the claim of generic coverage is wider than the seam delivers. afterError fires from Payload's own REST handler, so GET /api/events/geojson — which forwards the client's where verbatim and catches its own errors — still answers a flat 500 for exactly this failure class on an enum column the OpenAPI docs invite callers to filter on. Either map it there too or narrow the sentence. Beyond that: the response body invents a name field that is outside the ErrorResponse schema this API publishes, and the rationale is now written out three times (module header, plugin header, docs/architecture.md) in a change whose logic is one predicate and one hook. Nothing here questions the design — mapping the database's own judgement rather than re-deriving it per field is the right call, and shipping the blunt 400 as a floor is the right sequencing.

Not flagged, but stated so the decision is visible: the 400 forwards Postgres's message verbatim, so enum_meditations_type becomes client-visible; given debug: true in src/payload.config.ts:54 already returns stacks (filed as #684), this narrows rather than widens the leak. And a non-numeric id now yields 400 rather than 404, which #670's acceptance criteria explicitly allowed either way.

Findings

  • should-fix — docs/architecture.md:221: "covers every enum, id and date cast" does not hold for custom endpoints that catch their own errors; src/collections/Events/endpoints/geojson.ts:118-133 still 500s on where[eventType][equals]=bogus.
  • should-fix — src/plugins/databaseErrors/databaseErrorPlugin.ts:72: name: 'BadRequest' is outside the published ErrorResponse schema and unlike every other error body in this repo.
  • consider — src/plugins/sentry/sentryPlugin.ts:117: suppression keys on the error class, not on whose value it was; && req.user would keep a trace when the bad value is ours.
  • consider — src/lib/databaseErrors/index.ts:8: four files across two new directories for one predicate and one hook.
  • consider — src/lib/databaseErrors/postgresCastError.ts:24: the rationale is told three times, and line 72's ⚠ block narrates a review round rather than the code.

What was checked

  • Ticket #670 read in full against the diff — approach, all seven acceptance criteria, the two ⚠ premises, and the one open product decision (Path/lesson, recorded in the module header as the ticket asked).
  • Diff from the attached checkout: git diff origin/main...origin/claude/fix-22p02-cast-400 — 9 files, +524/-0, commits 03341d5 and fcfb8f3.
  • Payload internals, since this repo has no node_modules here: fetched [email protected]'s dist/utilities/{routeError,formatErrors,isErrorPublic}.js and read them. Confirms (a) hook return values re-shape response and status, (b) multiple afterError hooks reduce without clobbering, (c) logError runs at ERROR with the stack before any hook — so the PR's "the WARN is additive" caveat is accurate, and (d) formatErrors emits name only for an APIError/ValidationError carrying data, which is the basis of the second finding.
  • Consumer side. Grepped WeMeditateWeb and SahajAtlasWeb for daily_fallback_shri_mataji_clip and for a meditations type filter: no in-tree client sends either value, so the 500→400 change breaks no repo in this workspace, and the failing client is external. SahajAtlasWeb/src/config/api/mutate.ts:59-105 reads errors[].message and errors[].code / errors[].data.code — it tolerates an extra name, but it is not a consumer of one either.
  • Contract surfaces in-repo: src/plugins/openapi/customEndpoints.ts:224-237 and the ErrorResponse schema at :1585-1605; the ~20 hand-built { errors: [{ message }] } bodies across src/lib/endpoints/, src/endpoints/atlas/, src/collections/*/endpoints/.
  • Reach of the seam: read every custom endpoint that catches its own errors — Events/endpoints/geojson.ts, endpoints/atlas/seo/index.ts, endpoints/atlas/sitemap/index.ts — and confirmed Events.ts:348-353 makes eventType a select, hence an enum column, which is what makes the geojson gap concrete rather than theoretical.
  • Log convention: src/plugins/usage/hooks.ts:180-210 — the new WARN matches the existing payload.logger.warn({ msg, clientId: req.user?.id, … }) shape exactly, as #670 asked.
  • Specs: both new files read. The integration spec drives a real Postgres for both live cases and pins the cause shape rather than a fixture; the unit spec's ECONNRESET decoy is the one that would fail against the pre-fcfb8f3 walker. Not re-run — CI is green on fcfb8f3.
  • Reviewer profile (workflow/skills/adversarial-review/reviewer-profile.md) read and applied; no findings raised on style, naming, or test volume.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

Comment thread docs/architecture.md Resolved
Comment thread src/plugins/sentry/sentryPlugin.ts Resolved
Comment thread src/lib/databaseErrors/index.ts Resolved
…`name`

Answers my own adversarial review on #685. Two should-fix findings acted on,
two consider adopted, one rebutted with evidence.

**The coverage claim was wider than the seam reaches, and geojson was the
concrete gap.** Root `afterError` hooks are invoked by payload's
`dist/utilities/routeError.js`, so a custom endpoint that catches its own
errors never reaches the plugin. `Events/endpoints/geojson.ts` forwards the
client's `where` verbatim onto `eventType`, a Postgres enum column the OpenAPI
docs advertise filtering on — so `where[eventType][equals]=bogus` was still a
flat 500 naming nothing, with no Sentry event either, on a documented client
route. It now calls `mapPostgresCastError` in its own catch, and
`docs/architecture.md` states the seam's real reach plus the obligation any
future self-catching handler inherits.

The regression case is in `tests/int/events-geojson.int.spec.ts`, driven
against a real Postgres because the SQLSTATE is the whole assertion. Watched
failing at the site that causes it — with the catch reverted it reports
`expected 500 to be 400`; restored, 23/23.

**`name: 'BadRequest'` is gone.** It was outside the published `ErrorResponse`
schema (`plugins/openapi/customEndpoints.ts`), unlike ~20 other error bodies
here, and carried nothing the 400 status did not. Replaced with
`code: '22P02'`, which *is* in the schema and lets a client branch on the
cause without parsing Postgres prose.

**Folded `postgresCastError.ts` into `lib/databaseErrors/index.ts`** — the
import path is byte-identical, and one file now holds the idea instead of a
header, a barrel and a plugin barrel each restating it. The rationale was
told three times (module header, both plugin comments, `docs/architecture.md`);
the code now carries the imperatives and the doc carries the story, and the
⚠ block that narrated a review round is one line.

**Not adopted: discriminating the Sentry suppression on `req.user`.** It would
change nothing. `hasPermission` returns false for a null user
(`plugins/access/permissions.ts:59`) and no collection overrides `read`
publicly, so an anonymous read is denied before any SQL runs — `req.user` is
set on every error that can reach these hooks, including a 22P02 our own code
composed during a client's request, which is the case it was meant to catch.
What does preserve the signal is already there: `routeError` calls `logError`
at ERROR with the full stack before any hook runs. Written down in
`docs/architecture.md` so it is not re-proposed.

Gate: lint, typecheck, typecheck:tests, test:unit (120 files / 1553 specs),
plus `tests/int/{events-geojson,database-cast-errors}.int.spec.ts` — all green.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BG2uTcLbYEjqrx62vc7yAS
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-685 September 3, 2026 14:13 Destroyed
@sydevs-bot sydevs-bot changed the title fix(api): map a Postgres 22P02 cast failure to 400, instead of returning a 500 fix(api): map a Postgres 22P02 cast failure to 400, on Payload's routes and in geojson Sep 3, 2026
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

My own review found a real gap and it is fixed: GET /api/events/geojson was still answering 500 for exactly this failure class, on a documented client route. Four of the five findings adopted in cfbab29; one declined with evidence and left open for you.

Finding Outcome
should-fix Coverage claim wider than the afterError seam reaches Both halves — geojson maps it directly; the doc states the reach and the obligation
should-fix name: 'BadRequest' outside the published ErrorResponse schema Adopted — now code: '22P02', which is in-schema
consider Four files across two directories Adopted — folded into one; import path unchanged
consider The rationale told three times Adopted — header ~70 lines → ~20; the doc carries the story
consider Discriminate the Sentry suppression on req.user Declined, thread left open — it cannot discriminate; see below

The one that needs no decision from you but is worth reading. The req.user discriminator would change nothing: hasPermission returns false for a null user (plugins/access/permissions.ts:59) and no collection overrides read publicly, so an anonymous read is denied before any SQL runs — req.user is set on every error that can reach these hooks, including a 22P02 our own code composes during a client's request, which is the case it was meant to catch. A job's query never reaches the hook at all; routeError is its only invoker. What preserves the signal already exists: routeError logs at ERROR with the full stack before any hook runs, so these are absent from Sentry but never invisible. Written into docs/architecture.md so it is not re-proposed — and left unresolved so you can overrule it.

The regression case, and the gate

Watched failing at the site that causes it, per docs/rules/testing-reqs.md. tests/int/events-geojson.int.spec.ts drives the handler against a real Postgres, because the SQLSTATE is the whole assertion and a mocked find could only re-assert its own fixture:

× returns 400 naming the value when a where filter fails an enum cast
AssertionError: expected 500 to be 400

with the new catch reverted; 23/23 with it restored, and the WARN confirms the value reaches the caller — invalid input value for enum …enum_events_event_type: "bogus", sqlstate: "22P02".

The other two self-catching handlers were checked before concluding geojson was the only one owed a call: endpoints/atlas/{seo,sitemap} take a route and a client id, neither of which reaches a cast.

Gate, all green in the checkout: pnpm lint (exit 0), pnpm typecheck (0), pnpm typecheck:tests (0), pnpm test:unit (120 files / 1553 specs), tests/int/events-geojson.int.spec.ts (23), tests/int/database-cast-errors.int.spec.ts (3).

Diff since the review: 8 files, docs/architecture.md, src/lib/databaseErrors/ (two files → one), src/plugins/databaseErrors/{index,databaseErrorPlugin}.ts, src/plugins/sentry/sentryPlugin.ts, src/collections/Events/endpoints/geojson.ts, tests/int/events-geojson.int.spec.ts. Title and body refreshed against it.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@Ardnived Ardnived left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks good. We accept the decision to not change the discriminator raised by the adversarial review.

@sydevs-bot
sydevs-bot merged commit 01fe6a6 into main Sep 3, 2026
2 checks passed
Ardnived pushed a commit that referenced this pull request Nov 5, 2026
…`name`

Answers my own adversarial review on #685. Two should-fix findings acted on,
two consider adopted, one rebutted with evidence.

**The coverage claim was wider than the seam reaches, and geojson was the
concrete gap.** Root `afterError` hooks are invoked by payload's
`dist/utilities/routeError.js`, so a custom endpoint that catches its own
errors never reaches the plugin. `Events/endpoints/geojson.ts` forwards the
client's `where` verbatim onto `eventType`, a Postgres enum column the OpenAPI
docs advertise filtering on — so `where[eventType][equals]=bogus` was still a
flat 500 naming nothing, with no Sentry event either, on a documented client
route. It now calls `mapPostgresCastError` in its own catch, and
`docs/architecture.md` states the seam's real reach plus the obligation any
future self-catching handler inherits.

The regression case is in `tests/int/events-geojson.int.spec.ts`, driven
against a real Postgres because the SQLSTATE is the whole assertion. Watched
failing at the site that causes it — with the catch reverted it reports
`expected 500 to be 400`; restored, 23/23.

**`name: 'BadRequest'` is gone.** It was outside the published `ErrorResponse`
schema (`plugins/openapi/customEndpoints.ts`), unlike ~20 other error bodies
here, and carried nothing the 400 status did not. Replaced with
`code: '22P02'`, which *is* in the schema and lets a client branch on the
cause without parsing Postgres prose.

**Folded `postgresCastError.ts` into `lib/databaseErrors/index.ts`** — the
import path is byte-identical, and one file now holds the idea instead of a
header, a barrel and a plugin barrel each restating it. The rationale was
told three times (module header, both plugin comments, `docs/architecture.md`);
the code now carries the imperatives and the doc carries the story, and the
⚠ block that narrated a review round is one line.

**Not adopted: discriminating the Sentry suppression on `req.user`.** It would
change nothing. `hasPermission` returns false for a null user
(`plugins/access/permissions.ts:59`) and no collection overrides `read`
publicly, so an anonymous read is denied before any SQL runs — `req.user` is
set on every error that can reach these hooks, including a 22P02 our own code
composed during a client's request, which is the case it was meant to catch.
What does preserve the signal is already there: `routeError` calls `logError`
at ERROR with the full stack before any hook runs. Written down in
`docs/architecture.md` so it is not re-proposed.

Gate: lint, typecheck, typecheck:tests, test:unit (120 files / 1553 specs),
plus `tests/int/{events-geojson,database-cast-errors}.int.spec.ts` — all green.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BG2uTcLbYEjqrx62vc7yAS

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-685 — cfbab29e Deployed Sep 3, 2026 by railway-app[bot]
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.

fix(api): map a Postgres 22P02 cast failure to 400, instead of returning a 500

3 participants