The best way to control Claude Code, Codex and more from any computer or phone

main
ts 232 lines 7.6 KB
Raw
1 // Runtime error taxonomy for the Prisma ORM v8 Effect client. Worker-safe:
2 // imports nothing beyond effect, and detects Prisma's error shapes
3 // structurally (via their stable `kind` / `code` / `sqlState` discriminants)
4 // so this module never has to value-import the optional peer.
5 //
6 // Granularity policy: a dedicated tag wherever the discriminant is STABLE
7 // and handling genuinely branches — the SQL-standard integrity-violation
8 // SQLSTATEs (23xxx) and Prisma's error categories (`ORM.*`,
9 // `RUNTIME.*`, ...). Individual codes stay a typed `code` field rather than
10 // one class per code: the code set churns per RC, while categories and
11 // SQLSTATEs do not.
12 import * as Data from "effect/Data";
13
14 /**
15 * Prisma structured error codes observed in 8.0.0-rc.8 — an OPEN union
16 * (`string` stays assignable) so new RC codes never break, while known ones
17 * autocomplete.
18 */
19 export type ErrorCode =
20 | "ORM.TABLE_UNKNOWN"
21 | "ORM.COLUMN_UNKNOWN"
22 | "ORM.RELATION_UNKNOWN"
23 | "ORM.INCLUDE_INVALID"
24 | "ORM.AGGREGATE_UNSUPPORTED"
25 | "ORM.MUTATION_ROW_MISSING"
26 | "ORM.CAPABILITY_MISSING"
27 | "RUNTIME.ENCODE_FAILED"
28 | "RUNTIME.DECODE_FAILED"
29 | "RUNTIME.ABORTED"
30 | "RUNTIME.CODEC_MISSING"
31 | "RUNTIME.PREPARE_UNUSED_PARAM"
32 | "RUNTIME.PREPARE_BIND_ON_ADHOC"
33 | "RUNTIME.TRANSACTION_CLOSED"
34 | "RUNTIME.TRANSACTION_COMMIT_FAILED"
35 | "RUNTIME.TRANSACTION_ROLLBACK_FAILED"
36 | "RUNTIME.BINDING_INVALID"
37 | "RUNTIME.BINDING_MISSING"
38 | "BUDGET.ROWS_EXCEEDED"
39 | "DRIVER.NOT_CONNECTED"
40 | "DRIVER.ALREADY_CONNECTED"
41 | "DRIVER.PREPARE_FAILED"
42 | "CONTRACT.MARKER_MISSING"
43 | "CONTRACT.MARKER_MISMATCH"
44 | "CONTRACT.VERIFY_FAILED"
45 | (string & {});
46
47 interface QueryErrorFields {
48 message: string;
49 sqlState?: string | undefined;
50 constraint?: string | undefined;
51 table?: string | undefined;
52 column?: string | undefined;
53 detail?: string | undefined;
54 cause: unknown;
55 }
56
57 // ── integrity violations (SQL-standard SQLSTATE class 23) ─────────────
58 // The driver normalizes target codes onto SQLSTATE, so these tags are
59 // stable across databases and RCs.
60
61 /**
62 * Unique or primary-key conflict (SQLSTATE `23505`) — the "email already
63 * registered" case:
64 *
65 * ```typescript
66 * Effect.catchTag("Prisma.UniqueViolationError", () =>
67 * Effect.succeed("already registered"),
68 * )
69 * ```
70 */
71 export class UniqueViolationError extends Data.TaggedError(
72 "Prisma.UniqueViolationError",
73 )<QueryErrorFields> {}
74
75 /** Foreign-key violation (SQLSTATE `23503`) — a referenced row is missing. */
76 export class ForeignKeyViolationError extends Data.TaggedError(
77 "Prisma.ForeignKeyViolationError",
78 )<QueryErrorFields> {}
79
80 /** NOT NULL violation (SQLSTATE `23502`). */
81 export class NotNullViolationError extends Data.TaggedError(
82 "Prisma.NotNullViolationError",
83 )<QueryErrorFields> {}
84
85 /** CHECK constraint violation (SQLSTATE `23514`). */
86 export class CheckViolationError extends Data.TaggedError(
87 "Prisma.CheckViolationError",
88 )<QueryErrorFields> {}
89
90 /** Every integrity-constraint tag (SQLSTATE class 23). */
91 export type ConstraintViolationError =
92 | UniqueViolationError
93 | ForeignKeyViolationError
94 | NotNullViolationError
95 | CheckViolationError;
96
97 // ── other SQL / connection failures ───────────────────────────────────
98
99 /**
100 * Any other SQL statement failure (syntax, permissions, serialization,
101 * ...). `sqlState` carries the driver-normalized SQLSTATE for finer
102 * refinement.
103 */
104 export class QueryError extends Data.TaggedError("Prisma.QueryError")<QueryErrorFields> {}
105
106 /**
107 * A connection-level failure (refused, reset, timed out). `transient`
108 * carries the driver's own judgment of retryability:
109 *
110 * ```typescript
111 * Effect.retry(effect, {
112 * while: (e) => e._tag === "Prisma.ConnectionError" && e.transient === true,
113 * times: 3,
114 * })
115 * ```
116 */
117 export class ConnectionError extends Data.TaggedError("Prisma.ConnectionError")<{
118 message: string;
119 transient?: boolean | undefined;
120 cause: unknown;
121 }> {}
122
123 // ── Prisma pipeline categories ────────────────────────────────────────
124
125 /**
126 * ORM-lane misuse or validation failure (`ORM.*` codes: unknown
127 * table/column/relation, invalid include, unsupported aggregate, ...).
128 * Almost always a programming bug — don't retry.
129 */
130 export class OrmError extends Data.TaggedError("Prisma.OrmError")<{
131 code: ErrorCode;
132 message: string;
133 cause: unknown;
134 }> {}
135
136 /**
137 * Execution-pipeline failure (`RUNTIME.*`, `DRIVER.*`, `BUDGET.*`,
138 * `CONTRACT.*`, `PLAN.*`, `LINT.*`, `MIGRATION.*` codes: encode/decode,
139 * codec registry, transaction lifecycle, row budgets, marker
140 * verification, ...). `code` pins the exact failure.
141 */
142 export class RuntimeError extends Data.TaggedError("Prisma.RuntimeError")<{
143 code: ErrorCode;
144 message: string;
145 cause: unknown;
146 }> {}
147
148 /** A failure Prisma did not classify at all (no kind, no code). */
149 export class UnknownError extends Data.TaggedError("Prisma.UnknownError")<{
150 code?: ErrorCode | undefined;
151 message: string;
152 cause: unknown;
153 }> {}
154
155 /**
156 * Deliberate transaction rollback. Yield `tx.rollback()` inside
157 * `db.transaction` to abort: the transaction rolls back and this error
158 * surfaces in the caller's error channel, catchable with
159 * `Effect.catchTag("Prisma.RollbackError", ...)`.
160 */
161 export class RollbackError extends Data.TaggedError("Prisma.RollbackError")<{}> {}
162
163 /** Everything a Prisma query can fail with. */
164 export type ClientError =
165 | ConstraintViolationError
166 | QueryError
167 | ConnectionError
168 | OrmError
169 | RuntimeError
170 | UnknownError;
171
172 const field = (value: unknown, key: string): string | undefined => {
173 if (typeof value !== "object" || value === null) return undefined;
174 const v = (value as Record<string, unknown>)[key];
175 return typeof v === "string" ? v : undefined;
176 };
177
178 const message = (cause: unknown): string =>
179 cause instanceof Error ? cause.message : String(cause);
180
181 /**
182 * The single funnel converting Prisma's thrown errors into the typed
183 * taxonomy. Detection uses stable discriminants: `kind: 'sql_query' |
184 * 'sql_connection'` on driver errors (with SQLSTATE refining the class-23
185 * integrity violations onto their own tags), and the `CATEGORY.NAME`
186 * structured `code` on ORM/pipeline errors.
187 */
188 export const wrapPrismaError = (cause: unknown): ClientError => {
189 const kind = field(cause, "kind");
190 if (kind === "sql_query") {
191 const fields: QueryErrorFields = {
192 message: message(cause),
193 sqlState: field(cause, "sqlState"),
194 constraint: field(cause, "constraint"),
195 table: field(cause, "table"),
196 column: field(cause, "column"),
197 detail: field(cause, "detail"),
198 cause,
199 };
200 switch (fields.sqlState) {
201 case "23505":
202 return new UniqueViolationError(fields);
203 case "23503":
204 return new ForeignKeyViolationError(fields);
205 case "23502":
206 return new NotNullViolationError(fields);
207 case "23514":
208 return new CheckViolationError(fields);
209 default:
210 return new QueryError(fields);
211 }
212 }
213 if (kind === "sql_connection") {
214 const transient = (cause as { transient?: unknown }).transient;
215 return new ConnectionError({
216 message: message(cause),
217 transient: typeof transient === "boolean" ? transient : undefined,
218 cause,
219 });
220 }
221 const code = field(cause, "code");
222 if (code !== undefined) {
223 return code.startsWith("ORM.")
224 ? new OrmError({ code, message: message(cause), cause })
225 : new RuntimeError({ code, message: message(cause), cause });
226 }
227 return new UnknownError({
228 code: undefined,
229 message: message(cause),
230 cause,
231 });
232 };