Skip to content

Commit cfbab29

Browse files
committed
fix(api): map the cast error in geojson too, and drop the off-schema 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
1 parent fcfb8f3 commit cfbab29

8 files changed

Lines changed: 174 additions & 165 deletions

File tree

‎docs/architecture.md‎

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -218,12 +218,20 @@ WARN through `payload.logger`, and `@/plugins/sentry` asks the same predicate
218218
Errors of every other class are untouched: a genuine 500 stays a 500 and is still
219219
reported.
220220

221-
Generic over the SQLSTATE rather than over enums, so it covers every enum, id and
222-
date cast, present and future. The driver's `code` is matched down the `cause`
223-
chain, because drizzle wraps each failed query in a `Failed query: …` error;
221+
Generic over the SQLSTATE rather than over enums, so within its reach it covers every
222+
enum, id and date cast, present and future. The driver's `code` is matched down the
223+
`cause` chain, because drizzle wraps each failed query in a `Failed query: …` error;
224224
`tests/int/database-cast-errors.int.spec.ts` pins that shape against a real
225225
Postgres rather than a fixture.
226226

227+
⚠ **The hook's reach is Payload's own REST routes, not every route.** Root `afterError`
228+
hooks are invoked by `payload/dist/utilities/routeError.js`, so a custom endpoint that
229+
catches its own errors never reaches the hook and has to call `mapPostgresCastError`
230+
itself. `src/collections/Events/endpoints/geojson.ts` is the one that must: it forwards
231+
the client's `where` verbatim onto `eventType`, an enum column the OpenAPI docs advertise
232+
filtering on. Any future handler that catches its own errors and takes a client-supplied
233+
value inherits the same obligation — the predicate is exported for exactly this.
234+
227235
Two things it deliberately does not do, both worth knowing before you tune
228236
alerting on it:
229237

@@ -232,9 +240,13 @@ alerting on it:
232240
error (it keys on `err.name`, which `DrizzleQueryError` never sets). A rejected
233241
request emits both lines. Only the Sentry report is removed.
234242
- **It cannot tell whose bad value it was.** A 22P02 our *own* code causes — a
235-
derived id, a `where` composed from config, a job's own query — is now a 400
236-
blaming the caller, and is reported to Sentry nowhere. Accepted: the class is
237-
rare, the noise was not.
243+
derived id, a `where` composed from config — is now a 400 blaming the caller,
244+
and is reported to Sentry nowhere. Accepted: the class is rare, the noise was not,
245+
and the ERROR line above still fires for every one of them. Suppressing only for
246+
authenticated callers was considered and rejected: access control denies an
247+
anonymous read before any SQL runs (`hasPermission` returns `false` for no user),
248+
so `req.user` is set on every error that can reach these hooks and the test would
249+
never discriminate.
238250

239251
### Sentry integration
240252

‎src/collections/Events/endpoints/geojson.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import type { Endpoint, PopulateType, SelectType, Sort, Where } from 'payload'
33

44
import { APIError } from 'payload'
55

6+
import { INVALID_TEXT_REPRESENTATION, mapPostgresCastError } from '@/lib/databaseErrors'
67
import { requireActiveClient } from '@/lib/endpoints'
78
import type { Event } from '@/payload-types'
89
import { publicReadCacheHeaders } from '@/plugins/cache'
@@ -122,6 +123,25 @@ export const eventsGeoJson: Endpoint = {
122123
if (error instanceof APIError) {
123124
return Response.json({ errors: [{ message: error.message }] }, { status: error.status })
124125
}
126+
// This handler forwards the client's `where` verbatim, and `eventType` is a
127+
// Postgres enum column the OpenAPI docs invite callers to filter on — so
128+
// `where[eventType][equals]=bogus` raises SQLSTATE 22P02 here. Payload's root
129+
// `afterError` hook (`@/plugins/databaseErrors`) fires from `routeError`, which a
130+
// handler that catches its own errors never reaches, so the mapping is asked for
131+
// directly. (sydevs/SahajCloud#670)
132+
const mapped = mapPostgresCastError(error)
133+
if (mapped) {
134+
req.payload.logger.warn({
135+
msg: 'eventsGeoJson: rejected a request Postgres could not cast',
136+
clientId: req.user?.id,
137+
detail: mapped.message,
138+
sqlstate: INVALID_TEXT_REPRESENTATION,
139+
})
140+
return Response.json(
141+
{ errors: [{ code: INVALID_TEXT_REPRESENTATION, message: mapped.message }] },
142+
{ status: mapped.status },
143+
)
144+
}
125145
req.payload.logger.error({
126146
msg: 'eventsGeoJson: read failed',
127147
clientId: req.user?.id,

‎src/lib/databaseErrors/index.ts‎

Lines changed: 90 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,94 @@
11
/**
2-
* Database errors that are the caller's mistake rather than an incident.
2+
* Recognising a Postgres cast failure, and deciding what to answer for it.
33
*
4-
* One cohesive surface, imported as a unit by the plugin that answers with it
5-
* and by the Sentry plugin that declines to report it.
4+
* A caller-supplied value that Postgres cannot cast to a column's type raises
5+
* SQLSTATE **`22P02` (`invalid_text_representation`)**, and until this module
6+
* existed every one of them surfaced as a `500`. Two are live in production and
7+
* are the same error class one type apart:
8+
*
9+
* - `invalid input value for enum enum_meditations_type: "path"`
10+
* on `GET /api/meditations?where[type][equals]=path`
11+
* - `invalid input syntax for type integer: "NaN"`
12+
* on `GET /api/lectures/daily_fallback_shri_mataji_clip`
13+
*
14+
* Pure by design: no Payload types, no request, no logging. `@/plugins/databaseErrors`
15+
* answers with it on Payload's own REST routes, `@/plugins/sentry` asks it whether an
16+
* error is a caller's mistake before reporting an incident, and a custom endpoint that
17+
* catches its own errors calls it directly. The reasoning — why the error is matched
18+
* rather than the query pre-validated, and what the seam does and does not reach — is in
19+
* `docs/architecture.md`; the decision that `lesson` (not `Path`) is the in-code name is
20+
* on sydevs/SahajCloud#670.
21+
*/
22+
23+
/** SQLSTATE `22P02` — `invalid_text_representation`. */
24+
export const INVALID_TEXT_REPRESENTATION = '22P02'
25+
26+
/** How far down the `cause` chain to look. Drizzle adds one level; allow for more. */
27+
const MAX_CAUSE_DEPTH = 10
28+
29+
/** The subset of `pg`'s `DatabaseError` this module reads. */
30+
export type PostgresErrorLike = {
31+
code: string
32+
message: string
33+
}
34+
35+
/** What a recognised cast failure should be answered with. */
36+
export type MappedClientError = {
37+
message: string
38+
status: number
39+
}
40+
41+
const isPostgresErrorLike = (value: unknown): value is PostgresErrorLike =>
42+
typeof value === 'object' &&
43+
value !== null &&
44+
typeof (value as { code?: unknown }).code === 'string' &&
45+
typeof (value as { message?: unknown }).message === 'string'
46+
47+
/**
48+
* The first error in `error`'s `cause` chain whose driver `code` is `code`.
49+
*
50+
* Drizzle wraps every failed query in a `DrizzleQueryError` (`drizzle-orm/pg-core/session.js`)
51+
* keeping `pg`'s `DatabaseError` — and with it the SQLSTATE — on `cause`, so the chain is
52+
* walked rather than the message matched.
53+
*
54+
* ⚠ **Match the code; never stop at the first error that carries one.** Anything between
55+
* Payload and the driver may set a `code` of its own (a `SystemError` such as
56+
* `ECONNRESET`), and stopping there is silent — no 22P02 found, the 500 comes back.
57+
* The `ECONNRESET` decoy in `tests/unit/postgres-cast-error.spec.ts` pins it.
58+
*
59+
* Returns `null` rather than throwing on a cycle or a non-error — this runs on the error
60+
* path, where a second failure would replace a bad response with no response at all.
61+
*/
62+
export function findPostgresError(error: unknown, code: string): null | PostgresErrorLike {
63+
const seen = new Set<unknown>()
64+
let current = error
65+
66+
for (let depth = 0; depth <= MAX_CAUSE_DEPTH; depth++) {
67+
if (current === null || typeof current !== 'object' || seen.has(current)) return null
68+
if (isPostgresErrorLike(current) && current.code === code) return current
69+
seen.add(current)
70+
current = (current as { cause?: unknown }).cause
71+
}
72+
73+
return null
74+
}
75+
76+
/**
77+
* `{ status, message }` when this error is a Postgres cast failure, `null` otherwise — in
78+
* which case nothing about the error's handling changes.
79+
*
80+
* The message names the offending value because Postgres does, and that is the whole
81+
* point of the 400: the caller can see what it sent. It names the Postgres *type*
82+
* (`enum_meditations_type`) rather than the field, because SQLSTATE 22P02 carries the
83+
* type and not the column — a worse-worded 400 that cannot miss a case, rather than a
84+
* better-worded one that only covers enums.
685
*/
86+
export function mapPostgresCastError(error: unknown): MappedClientError | null {
87+
const postgresError = findPostgresError(error, INVALID_TEXT_REPRESENTATION)
88+
if (!postgresError) return null
789

8-
export type { MappedClientError, PostgresErrorLike } from './postgresCastError'
9-
export {
10-
findPostgresError,
11-
INVALID_TEXT_REPRESENTATION,
12-
mapPostgresCastError,
13-
} from './postgresCastError'
90+
return {
91+
message: `Invalid value in request: ${postgresError.message}`,
92+
status: 400,
93+
}
94+
}

‎src/lib/databaseErrors/postgresCastError.ts‎

Lines changed: 0 additions & 116 deletions
This file was deleted.

‎src/plugins/databaseErrors/databaseErrorPlugin.ts‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,13 @@
1515
* ```
1616
*
1717
* So the response is rebuilt here rather than the query pre-validated. The
18-
* recognition itself is pure and lives in `@/lib/databaseErrors`; see that
19-
* module for why the driver error is reached through `cause` and why the
20-
* database is left to make the judgement. (sydevs/SahajCloud#670)
18+
* recognition itself is pure and lives in `@/lib/databaseErrors`; the reasoning is
19+
* in `docs/architecture.md`. (sydevs/SahajCloud#670)
2120
*
22-
* REST only. GraphQL takes its own error path and reads `graphqlResult`, which
23-
* this hook does not set.
21+
* ⚠ **Payload's own REST routes only.** `routeError` is what invokes root `afterError`
22+
* hooks, so a custom endpoint that catches its own errors never reaches this — it has to
23+
* call `mapPostgresCastError` itself, as `Events/endpoints/geojson.ts` does. GraphQL
24+
* likewise takes its own path and reads `graphqlResult`, which this hook does not set.
2425
*/
2526
import type { Config } from 'payload'
2627

@@ -68,8 +69,14 @@ export const databaseErrorPlugin =
6869
url: req.url,
6970
})
7071

72+
// `{ errors: [{ message, code }] }` is the shape every other error in this API
73+
// uses, and both keys are in the published `ErrorResponse` schema
74+
// (`@/plugins/openapi/customEndpoints`). The SQLSTATE is the machine-readable
75+
// half, so a client can branch on the cause without parsing Postgres prose.
7176
return {
72-
response: { errors: [{ name: 'BadRequest', message: mapped.message }] },
77+
response: {
78+
errors: [{ code: INVALID_TEXT_REPRESENTATION, message: mapped.message }],
79+
},
7380
status: mapped.status,
7481
}
7582
},
Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,6 @@
11
/**
2-
* Database Errors Plugin
3-
*
4-
* Turns a Postgres cast failure (SQLSTATE 22P02) into a 400 naming the
5-
* offending value, instead of an unhandled 500.
6-
*
7-
* @example
8-
* ```typescript
9-
* import { databaseErrorPlugin } from '@/plugins/databaseErrors'
10-
*
11-
* plugins: [
12-
* databaseErrorPlugin(),
13-
* ]
14-
* ```
2+
* Database Errors Plugin — turns a Postgres cast failure (SQLSTATE 22P02) into a 400
3+
* naming the offending value, instead of an unhandled 500. See `databaseErrorPlugin`.
154
*/
165

176
export { databaseErrorPlugin } from './databaseErrorPlugin'

‎src/plugins/sentry/sentryPlugin.ts‎

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -98,22 +98,16 @@ export const sentryPlugin = (options: SentryPluginOptions = {}) => {
9898
async (args) => {
9999
const { error, req } = args
100100

101-
// A Postgres cast failure is the caller sending a value the column
102-
// cannot hold — `@/plugins/databaseErrors` answers it with a 400 and
103-
// logs it at WARN, so it is diagnosable without being an incident.
104-
// Reporting it here would keep the noise this repo set out to remove,
105-
// and `captureErrors` includes 400, so restatusing alone would not.
106-
// Asking the same pure predicate rather than reading a flag the other
107-
// hook sets keeps this independent of the order the two are registered
108-
// in.
101+
// A Postgres cast failure is the caller sending a value the column cannot
102+
// hold, so it is a 400 rather than an incident. `captureErrors` includes 400,
103+
// so restatusing alone would not stop the report — and asking the same pure
104+
// predicate rather than reading a flag the other hook sets keeps this
105+
// independent of the order the two plugins are registered in.
109106
//
110-
// ⚠ **The accepted cost**: this keys on the SQLSTATE alone, so it
111-
// cannot tell a caller's bad value from one OUR code composed — a
112-
// derived id, a `where` built from config, a job's own query. Such a
113-
// defect is now a 400 blaming the client and reaches Sentry nowhere.
114-
// The trade was taken because the class is rare and the noise was
115-
// not; if one is ever suspected, the WARN line is where it shows up.
116-
// (sydevs/SahajCloud#670)
107+
// ⚠ **This suppresses a 22P02 OUR code composed too**, not only a caller's.
108+
// Do not try to discriminate on `req.user`: access control denies an
109+
// anonymous read before any SQL runs, so it is set on every error that
110+
// reaches here. `docs/architecture.md` has the trade. (sydevs/SahajCloud#670)
117111
if (mapPostgresCastError(error)) {
118112
return
119113
}

0 commit comments

Comments
 (0)