Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

errors: answer a caller's bad input with 400 or 404, not the driver's message

Carl-Gerhard Lindesvärd047ce12a109a
diff --git a/packages/core/src/modules/mcp/src/tools/shared.ts b/packages/core/src/modules/mcp/src/tools/shared.ts
index 7ca4c21f9..cf7b263ec 100644
--- a/packages/core/src/modules/mcp/src/tools/shared.ts
+++ b/packages/core/src/modules/mcp/src/tools/shared.ts
@@ -1,5 +1,6 @@
import { z } from 'zod';
import type { ServiceDeps, Services } from '../../../../services';
+import { classifyDriverError } from '../../../../shared/driver-errors';
import { resolveClientProjectId } from '../../../project/project.service';
import type { McpAuthContext } from '../auth';
@@ -355,8 +356,13 @@ export async function withErrorHandling<T>(
const result = await fn();
return toText(deps, result);
} catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- deps.logger.error({ err }, `MCP tool error: ${message}`);
+ const raw = err instanceof Error ? err.message : String(err);
+ // The model sees this text, so a driver failure must not hand it Prisma's
+ // invocation dump or a ClickHouse message quoting the generated SQL
+ // (ISSUES.md H12). The full error still goes to the log.
+ const failure = classifyDriverError(err);
+ const message = failure ? failure.message : raw;
+ deps.logger.error({ err }, `MCP tool error: ${raw}`);
return {
content: [{ type: 'text' as const, text: `Error: ${message}` }],
isError: true,
diff --git a/packages/core/src/rpc/base.ts b/packages/core/src/rpc/base.ts
index e5b3e77df..9f97fa906 100644
--- a/packages/core/src/rpc/base.ts
+++ b/packages/core/src/rpc/base.ts
@@ -16,6 +16,7 @@ import type { HttpCtx, Session } from '../context';
import type { Logger } from '../logger';
import { runWithAlsSession } from '../shared/als-session';
import { type CookieOptions, serializeCookie } from '../shared/cookie';
+import { classifyDriverError } from '../shared/driver-errors';
import { EMPTY_SESSION } from '../shared/session';
import { cancelledCallError, raceCancellation } from './deadline';
import { TRPCForbiddenError } from './errors';
@@ -114,7 +115,36 @@ const stopWhenCancelled = t.middleware(async ({ ctx, next }) => {
* only ones are the share-aware `chartProcedure`/`overviewProcedure` bases,
* and those are `publicProcedure` plus their own middleware.
*/
-export const procedure = t.procedure.use(stopWhenCancelled);
+/**
+ * Turns a driver failure caused by the CALLER into the status it deserves.
+ *
+ * A malformed id raised Prisma P2023 before any `findUnique` null check could
+ * run, so procedures with a perfectly good not-found guard still answered 500
+ * — with the driver's own message, which for ClickHouse echoes the generated
+ * SQL. Anything `classifyDriverError` does not recognise is rethrown
+ * untouched and stays a 500, because a query bug is not the caller's mistake.
+ *
+ * This sits on `procedure` itself, which every builder derives from, so all
+ * 177 procedures are covered by one `.use()`.
+ */
+const mapDriverErrors = t.middleware(async ({ next }) => {
+ const result = await next();
+ if (result.ok) {
+ return result;
+ }
+
+ const cause = result.error.cause;
+ const failure = classifyDriverError(cause);
+ if (!failure) {
+ return result;
+ }
+
+ throw new TRPCError({ code: failure.trpc, message: failure.message });
+});
+
+export const procedure = t.procedure
+ .use(stopWhenCancelled)
+ .use(mapDriverErrors);
// ---------------------------------------------------------------------------
// The procedure stack (M11-001), ported from packages/trpc/src/trpc.ts:35-155.
diff --git a/packages/core/src/shared/driver-errors.test.ts b/packages/core/src/shared/driver-errors.test.ts
new file mode 100644
index 000000000..3d3f37363
--- /dev/null
+++ b/packages/core/src/shared/driver-errors.test.ts
@@ -0,0 +1,72 @@
+// Both drivers label their failures, so the classifier reads labels and never
+// parses a message. The shapes below are what the real drivers throw — the
+// ClickHouse ones were taken from live errors against the worktree database.
+
+import { describe, expect, test } from 'bun:test';
+import { classifyDriverError } from './driver-errors';
+
+const prismaError = (code: string) =>
+ Object.assign(new Error('Invalid `prisma.client.findUnique()` invocation'), {
+ code,
+ });
+
+const clickhouseError = (code: string, type: string) =>
+ Object.assign(
+ new Error(
+ 'Cannot parse uuid nope: In scope SELECT count() FROM events WHERE project_id = ...'
+ ),
+ { code, type }
+ );
+
+describe('classifyDriverError', () => {
+ test('a malformed id on a @db.Uuid column is a 400, not a 500', () => {
+ expect(classifyDriverError(prismaError('P2023'))).toEqual({
+ trpc: 'BAD_REQUEST',
+ status: 400,
+ message: 'Malformed id',
+ });
+ });
+
+ test('a findUniqueOrThrow miss is a 404', () => {
+ expect(classifyDriverError(prismaError('P2025'))).toEqual({
+ trpc: 'NOT_FOUND',
+ status: 404,
+ message: 'Not found',
+ });
+ });
+
+ test("ClickHouse parse failures are the caller's own input", () => {
+ for (const [type, message] of [
+ ['CANNOT_PARSE_UUID', 'Malformed id'],
+ ['CANNOT_PARSE_DATETIME', 'Malformed date'],
+ ['INVALID_WITH_FILL_EXPRESSION', 'Invalid date range'],
+ ] as const) {
+ expect([type, classifyDriverError(clickhouseError('376', type))]).toEqual(
+ [type, { trpc: 'BAD_REQUEST', status: 400, message }]
+ );
+ }
+ });
+
+ test("the message never carries the driver's own words", () => {
+ const failure = classifyDriverError(
+ clickhouseError('376', 'CANNOT_PARSE_UUID')
+ );
+ expect(failure?.message).not.toContain('SELECT');
+ expect(failure?.message).not.toContain('scope');
+ });
+
+ // A query bug must not be reported to the caller as their mistake.
+ test('anything unrecognised stays a 500', () => {
+ for (const unknown of [
+ new Error('boom'),
+ prismaError('P1001'),
+ clickhouseError('241', 'MEMORY_LIMIT_EXCEEDED'),
+ null,
+ undefined,
+ 'a string',
+ { code: 42 },
+ ]) {
+ expect(classifyDriverError(unknown)).toBeNull();
+ }
+ });
+});
diff --git a/packages/core/src/shared/driver-errors.ts b/packages/core/src/shared/driver-errors.ts
new file mode 100644
index 000000000..3b0492acd
--- /dev/null
+++ b/packages/core/src/shared/driver-errors.ts
@@ -0,0 +1,81 @@
+// Postgres and ClickHouse failures that are really BAD INPUT, classified once
+// so every transport answers the same way.
+//
+// Without this a malformed id reached the caller as a 500 carrying the
+// driver's own words — Prisma's full invocation text, or a ClickHouse message
+// that echoes the generated SQL including its scope clause (ISSUES.md H12).
+//
+// Both drivers label their failures, so nothing here parses a message:
+// Prisma sets `code` to `P####`, and @clickhouse/client sets `code` to the
+// numeric error and `type` to its name.
+
+export interface DriverFailure {
+ /** tRPC's code; the HTTP status follows from it. */
+ trpc: 'BAD_REQUEST' | 'NOT_FOUND';
+ status: number;
+ /** Replaces the driver's message, which is not the caller's business. */
+ message: string;
+}
+
+const BAD_REQUEST = 400;
+const NOT_FOUND = 404;
+
+/** https://www.prisma.io/docs/orm/reference/error-reference */
+const PRISMA_FAILURES: Record<string, DriverFailure> = {
+ // "Inconsistent column data" — what an `@db.Uuid` column raises for an id
+ // that is not a UUID at all. It fires BEFORE any findUnique null check, so
+ // procedures with a correct not-found guard still answered 500.
+ P2023: {
+ trpc: 'BAD_REQUEST',
+ status: BAD_REQUEST,
+ message: 'Malformed id',
+ },
+ // "An operation failed because it depends on one or more records that were
+ // required but not found" — every `findUniqueOrThrow` miss.
+ P2025: {
+ trpc: 'NOT_FOUND',
+ status: NOT_FOUND,
+ message: 'Not found',
+ },
+};
+
+/**
+ * ClickHouse `type` values that can only come from caller input. Deliberately
+ * a short allowlist: anything unlisted stays a 500, because a query bug must
+ * not be reported to the caller as their mistake.
+ */
+const CLICKHOUSE_BAD_INPUT: Record<string, string> = {
+ CANNOT_PARSE_UUID: 'Malformed id',
+ CANNOT_PARSE_DATE: 'Malformed date',
+ CANNOT_PARSE_DATETIME: 'Malformed date',
+ CANNOT_PARSE_NUMBER: 'Malformed number',
+ INVALID_WITH_FILL_EXPRESSION: 'Invalid date range',
+};
+
+function readLabels(error: unknown): { code?: string; type?: string } {
+ if (typeof error !== 'object' || error === null) {
+ return {};
+ }
+ const labelled = error as { code?: unknown; type?: unknown };
+ return {
+ code: typeof labelled.code === 'string' ? labelled.code : undefined,
+ type: typeof labelled.type === 'string' ? labelled.type : undefined,
+ };
+}
+
+/** `null` when the failure is not the caller's fault — leave those as 500s. */
+export function classifyDriverError(error: unknown): DriverFailure | null {
+ const { code, type } = readLabels(error);
+
+ const prisma = code ? PRISMA_FAILURES[code] : undefined;
+ if (prisma) {
+ return prisma;
+ }
+
+ const clickhouse = type ? CLICKHOUSE_BAD_INPUT[type] : undefined;
+ if (clickhouse) {
+ return { trpc: 'BAD_REQUEST', status: BAD_REQUEST, message: clickhouse };
+ }
+
+ return null;
+}
diff --git a/packages/core/src/shared/errors.ts b/packages/core/src/shared/errors.ts
index de4d6ea7b..d2b0e755a 100644
--- a/packages/core/src/shared/errors.ts
+++ b/packages/core/src/shared/errors.ts
@@ -2,6 +2,8 @@
// and the Kafka consumer all throw and normalize through this, not through
// an rpc/-specific error type (see rpc/errors.ts for the TRPCError family).
+import { classifyDriverError } from './driver-errors';
+
const DEFAULT_HTTP_STATUS = 500;
export class LogError extends Error {
@@ -52,6 +54,19 @@ export interface NormalizedError {
}
export function normalizeError(error: unknown): NormalizedError {
+ // A driver failure the CALLER caused answers with its own status and a
+ // message that is not the driver's — Prisma's invocation text and
+ // ClickHouse's scope clause are not the caller's business (ISSUES.md H12).
+ const driverFailure = classifyDriverError(error);
+ if (driverFailure) {
+ return {
+ status: driverFailure.status,
+ code: undefined,
+ message: driverFailure.message,
+ errorName: 'Error',
+ };
+ }
+
if (error instanceof Error) {
const meta = error as Error & {
statusCode?: unknown;