mirror of
https://github.com/bitbaum/petvity.git
synced 2026-12-04 07:27:36 +01:00
Caught by exercising the live endpoint as an admin rather than trusting the unit test: creating a second post with an existing slug answered 500. Drizzle wraps driver errors, so the pg error carrying `code: 23505` is the `cause` of what the route catches, not the error itself. Reading only the top-level `code` looks correct in a test — where the error is hand-built with the code right on it — and is wrong against a real database. The test passed and production returned 500 for a mistake the author can fix in two seconds. isUniqueViolation now walks the cause chain, bounded, with a guard against a self-referencing chain hanging the request. Both tests now use the wrapped shape production actually throws, which is the point: the old test asserted the shape I assumed, not the shape reality produces. Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
31 lines
1.1 KiB
TypeScript
31 lines
1.1 KiB
TypeScript
/**
|
|
* Postgres error codes we act on.
|
|
*
|
|
* A unique-constraint violation is usually a user-correctable mistake (a slug
|
|
* already taken), not a server fault — telling them apart is the difference
|
|
* between a helpful 409 and a 500.
|
|
*/
|
|
const UNIQUE_VIOLATION = "23505";
|
|
|
|
/**
|
|
* Drizzle wraps driver errors, so the pg error carrying `code` is normally the
|
|
* `cause` of what the caller catches — sometimes nested more than once. Reading
|
|
* only the top-level `code` looks correct in a unit test (where the error is
|
|
* hand-built) and silently returns a 500 in production. Verified against the
|
|
* live endpoint: a duplicate slug threw a wrapped error and answered 500 until
|
|
* this walked the cause chain.
|
|
*/
|
|
export function isUniqueViolation(e: unknown): boolean {
|
|
for (let cur: unknown = e, depth = 0; cur && depth < 5; depth++) {
|
|
if (
|
|
typeof cur === "object" &&
|
|
"code" in cur &&
|
|
(cur as { code?: unknown }).code === UNIQUE_VIOLATION
|
|
) {
|
|
return true;
|
|
}
|
|
cur = typeof cur === "object" && "cause" in cur ? (cur as { cause?: unknown }).cause : null;
|
|
}
|
|
return false;
|
|
}
|