Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(trpc): hand the client a searchable reference instead of raw database SQL (#20558)

Arvin Xufbab315daa71
diff --git a/packages/trpc/src/lambda/index.ts b/packages/trpc/src/lambda/index.ts
index 62030326caf..103586f98f5 100644
--- a/packages/trpc/src/lambda/index.ts
+++ b/packages/trpc/src/lambda/index.ts
@@ -8,6 +8,7 @@
* @link https://trpc.io/docs/v11/procedures
*/
+import { databaseError } from '../middleware/databaseError';
import { openTelemetry } from '../middleware/openTelemetry';
import { upstreamError } from '../middleware/upstreamError';
import { userAuth } from '../middleware/userAuth';
@@ -26,7 +27,7 @@ export const router = trpc.router;
* Create an unprotected procedure
* @link https://trpc.io/docs/v11/procedures
**/
-const baseProcedure = trpc.procedure.use(openTelemetry).use(upstreamError);
+const baseProcedure = trpc.procedure.use(openTelemetry).use(upstreamError).use(databaseError);
// `apiKeyScopeGuard` also covers public procedures: `createLambdaContext`
// authenticates an `X-API-Key` before procedure selection, and several public
diff --git a/packages/trpc/src/middleware/databaseError.test.ts b/packages/trpc/src/middleware/databaseError.test.ts
new file mode 100644
index 00000000000..299bc35a35e
--- /dev/null
+++ b/packages/trpc/src/middleware/databaseError.test.ts
@@ -0,0 +1,231 @@
+import { TRPCError } from '@trpc/server';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createCallerFactory } from '@/libs/trpc/lambda';
+import { createContextInner } from '@/libs/trpc/lambda/context';
+
+import { trpc } from '../lambda/init';
+import {
+ createDatabaseErrorRef,
+ databaseError,
+ isDrizzleQueryError,
+ toDatabaseTRPCError,
+} from './databaseError';
+
+/**
+ * The driver error both `postgres` and the Neon serverless driver throw.
+ */
+const postgresError = (props: Record<string, unknown>) =>
+ Object.assign(new Error(String(props.message ?? 'database error')), props);
+
+/**
+ * A realistic Drizzle wrapper; `message` and the fixture body mirror what
+ * production actually serialises onto the wire.
+ */
+const drizzleQueryError = (cause?: unknown) =>
+ Object.assign(
+ new Error(
+ 'Failed query: insert into "messages" ("id", "role", "content") values ($1, $2, $3)\nparams: msg_1,user,a user message',
+ ),
+ {
+ cause,
+ name: 'DrizzleQueryError',
+ params: 'msg_1,user,a user message',
+ query: 'insert into "messages" ("id", "role", "content") values ($1, $2, $3)',
+ },
+ );
+
+/** Every message in the cause chain β€” what the server log prints via `cause`. */
+const collectChainMessages = (error: unknown): string[] => {
+ const messages: string[] = [];
+ let current: unknown = error;
+
+ while (current instanceof Error) {
+ messages.push(current.message);
+ current = current.cause;
+ }
+
+ return messages;
+};
+
+const selectLog = (overrides: Record<string, unknown> = {}) => ({
+ code: '23503',
+ column: 'workspace_id',
+ constraint: 'messages_workspace_id_workspaces_id_fk',
+ message: 'insert or update on table "messages" violates foreign key constraint',
+ table: 'messages',
+ ...overrides,
+});
+
+describe('isDrizzleQueryError', () => {
+ it('recognises the wrapper by name', () => {
+ expect(isDrizzleQueryError(drizzleQueryError())).toBe(true);
+ });
+
+ it('recognises the wrapper by shape when the class identity is lost', () => {
+ // Bundler boundaries hand us a plain object carrying the same fields.
+ expect(
+ isDrizzleQueryError({
+ message: 'Failed query: begin params: ',
+ params: '',
+ query: 'begin',
+ }),
+ ).toBe(true);
+ });
+
+ it('ignores unrelated errors that merely mention "params:"', () => {
+ expect(isDrizzleQueryError(new Error('invalid params: missing field'))).toBe(false);
+ expect(isDrizzleQueryError(undefined)).toBe(false);
+ });
+});
+
+describe('toDatabaseTRPCError', () => {
+ it('replaces the SQL dump with a message carrying only the reference', () => {
+ const original = new TRPCError({
+ cause: drizzleQueryError(postgresError(selectLog())),
+ code: 'INTERNAL_SERVER_ERROR',
+ });
+
+ const mapped = toDatabaseTRPCError(original, { createRef: () => 'db_testref0001' });
+
+ expect(mapped).toBeInstanceOf(TRPCError);
+ expect(mapped!.code).toBe('INTERNAL_SERVER_ERROR');
+ expect(mapped!.message).toBe('Internal server error (ref: db_testref0001)');
+ // The regression: the client used to receive the statement plus its params.
+ expect(mapped!.message).not.toContain('Failed query');
+ expect(mapped!.message).not.toContain('params:');
+ expect(mapped!.message).not.toContain('a user message');
+ });
+
+ it('keeps the original error as `cause` so the server log still holds the SQL', () => {
+ const original = new TRPCError({
+ cause: drizzleQueryError(postgresError(selectLog())),
+ code: 'INTERNAL_SERVER_ERROR',
+ });
+
+ const mapped = toDatabaseTRPCError(original, { createRef: () => 'db_testref0002' })!;
+
+ expect(mapped.cause).toBe(original);
+ expect(collectChainMessages(mapped).join('\n')).toContain('Failed query:');
+ expect(collectChainMessages(mapped).join('\n')).toContain('violates foreign key constraint');
+ });
+
+ it('logs the reference next to the SQLSTATE and constraint', () => {
+ const log = vi.fn();
+ const original = new TRPCError({
+ cause: drizzleQueryError(postgresError(selectLog())),
+ code: 'INTERNAL_SERVER_ERROR',
+ });
+
+ toDatabaseTRPCError(original, { createRef: () => 'db_testref0003', log });
+
+ expect(log).toHaveBeenCalledWith({
+ column: 'workspace_id',
+ constraint: 'messages_workspace_id_workspaces_id_fk',
+ error: original,
+ ref: 'db_testref0003',
+ sqlstate: '23503',
+ table: 'messages',
+ });
+ });
+
+ it('finds the wrapper deeper in the cause chain', () => {
+ const original = new TRPCError({
+ cause: new Error('reserve failed', { cause: drizzleQueryError(postgresError(selectLog())) }),
+ code: 'INTERNAL_SERVER_ERROR',
+ });
+
+ const mapped = toDatabaseTRPCError(original, { createRef: () => 'db_testref0004' });
+
+ expect(mapped!.message).toBe('Internal server error (ref: db_testref0004)');
+ });
+
+ it('still sanitises when only the wrapped message survived', () => {
+ const original = new TRPCError({
+ cause: new Error('Failed query: insert into "messages" ("id") values ($1)\nparams: msg_1'),
+ code: 'INTERNAL_SERVER_ERROR',
+ });
+
+ const mapped = toDatabaseTRPCError(original, { createRef: () => 'db_testref0005' });
+
+ expect(mapped!.message).not.toContain('Failed query');
+ });
+
+ it('leaves non-database 500s untouched', () => {
+ const original = new TRPCError({
+ cause: new Error('boom'),
+ code: 'INTERNAL_SERVER_ERROR',
+ });
+
+ expect(toDatabaseTRPCError(original)).toBeUndefined();
+ });
+
+ it('does not override codes routers chose deliberately', () => {
+ const original = new TRPCError({
+ cause: drizzleQueryError(postgresError(selectLog())),
+ code: 'CONFLICT',
+ });
+
+ expect(toDatabaseTRPCError(original)).toBeUndefined();
+ });
+});
+
+describe('createDatabaseErrorRef', () => {
+ it('produces a greppable, unique reference', () => {
+ const first = createDatabaseErrorRef();
+ const second = createDatabaseErrorRef();
+
+ expect(first).toMatch(/^db_[0-9a-f]{12}$/);
+ expect(first).not.toBe(second);
+ });
+});
+
+const createRouter = (thrown: unknown) => {
+ const appRouter = trpc.router({
+ run: trpc.procedure.use(databaseError).mutation(() => {
+ throw thrown;
+ }),
+ });
+
+ return createCallerFactory(appRouter);
+};
+
+const callWith = async (thrown: unknown) => {
+ const caller = createRouter(thrown)(await createContextInner());
+ return caller.run().catch((error: TRPCError) => error);
+};
+
+describe('databaseError middleware', () => {
+ it('hands the client a reference instead of the statement and its params', async () => {
+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ try {
+ const error = await callWith(drizzleQueryError(postgresError(selectLog())));
+
+ expect(error).toBeInstanceOf(TRPCError);
+ expect(error.message).toMatch(/^Internal server error \(ref: db_[0-9a-f]{12}\)$/);
+ expect(collectChainMessages(error).join('\n')).toContain('Failed query:');
+
+ // The reference the user is given is the one written next to the SQLSTATE,
+ // so the log line is reachable from the message alone.
+ const ref = error.message.match(/ref: (db_[0-9a-f]{12})/)?.[1];
+ expect(ref).toBeDefined();
+
+ const loggedLines = logged.mock.calls.map((args) => args.map(String).join(' ')).join('\n');
+ expect(loggedLines).toContain(`ref=${ref}`);
+ expect(loggedLines).toContain('sqlstate=23503');
+ // The statement itself is kept server-side under the same reference.
+ expect(loggedLines).toContain(`[db-error] ${ref} original`);
+ expect(loggedLines).toContain('Failed query:');
+ } finally {
+ logged.mockRestore();
+ }
+ });
+
+ it('leaves plain errors on their original message', async () => {
+ const error = await callWith(new Error('boom'));
+
+ expect(error.code).toBe('INTERNAL_SERVER_ERROR');
+ expect(error.message).toBe('boom');
+ });
+});
diff --git a/packages/trpc/src/middleware/databaseError.ts b/packages/trpc/src/middleware/databaseError.ts
new file mode 100644
index 00000000000..c1e5c87267b
--- /dev/null
+++ b/packages/trpc/src/middleware/databaseError.ts
@@ -0,0 +1,196 @@
+import { randomUUID } from 'node:crypto';
+
+import { TRPCError } from '@trpc/server';
+
+import { trpc } from '../lambda/init';
+
+/**
+ * Prefix of the reference we hand back to the client in place of a raw
+ * database error. Kept greppable on purpose: the same `ref` is written to the
+ * server log right next to the error it refers to, so support can go from a
+ * user-facing string to the exact failure without asking for a timestamp.
+ */
+export const DATABASE_ERROR_REF_PREFIX = 'db_';
+
+const MAX_CAUSE_DEPTH = 5;
+
+/** PostgreSQL SQLSTATEs are five digits / uppercase letters (`23503`, `23505`, ...). */
+const SQLSTATE_PATTERN = /^[0-9A-Z]{5}$/;
+
+interface DrizzleQueryErrorLike {
+ cause?: unknown;
+ message?: string;
+ name?: string;
+ params?: unknown;
+ query?: unknown;
+}
+
+interface PostgresErrorLike {
+ code?: string;
+ column?: string;
+ constraint?: string;
+ table?: string;
+}
+
+export interface DatabaseErrorLogEntry {
+ column?: string;
+ constraint?: string;
+ /** The error as it arrived, statement and bound values included. */
+ error: unknown;
+ ref: string;
+ sqlstate?: string;
+ table?: string;
+}
+
+export interface ToDatabaseTRPCErrorOptions {
+ /** Injectable for tests / callers that need deterministic references. */
+ createRef?: () => string;
+ /** Injectable for tests; production writes the two lines below. */
+ log?: (entry: DatabaseErrorLogEntry) => void;
+}
+
+const isObjectLike = (value: unknown): value is Record<string, unknown> =>
+ !!value && typeof value === 'object';
+
+/**
+ * Drizzle wraps every failed statement / transaction in a `DrizzleQueryError`
+ * whose `message` is `` `Failed query: <sql>\nparams: <bound values>` ``, and
+ * whose `cause` is the driver error.
+ *
+ * That wrapper message is what tRPC puts on the wire β€” and the chat input
+ * renders `error.message` verbatim β€” so a routine constraint violation reaches
+ * the user as a wall of SQL plus every bound parameter, including their own
+ * message body. Meanwhile the actionable part (SQLSTATE, constraint name) only
+ * exists on the driver error, which never leaves the server.
+ *
+ * We deliberately avoid `instanceof`: the error crosses bundler boundaries
+ * (app router / worker bundles carry their own copy of the class), so class
+ * identity is not stable. Match the shape Drizzle always produces instead.
+ */
+export const isDrizzleQueryError = (error: unknown): error is DrizzleQueryErrorLike => {
+ if (!isObjectLike(error)) return false;
+ if (error.name === 'DrizzleQueryError') return true;
+
+ return (
+ typeof error.message === 'string' &&
+ error.message.startsWith('Failed query:') &&
+ 'query' in error &&
+ 'params' in error
+ );
+};
+
+/**
+ * Walk the cause chain for the driver error. Both `postgres` and the Neon
+ * serverless driver expose the SQLSTATE on `code`, plus `constraint` / `table` /
+ * `column` for constraint violations.
+ *
+ * The agent-runtime side has its own richer unwrapper
+ * (`apps/server/src/modules/AgentRuntime/pgError.ts`) for the harness error
+ * records; it cannot be shared from here because a `packages/*` module must not
+ * depend on `apps/*`.
+ */
+const findPostgresError = (error: unknown): PostgresErrorLike | undefined => {
+ let current: unknown = error;
+
+ for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {
+ if (
+ isObjectLike(current) &&
+ typeof current.code === 'string' &&
+ SQLSTATE_PATTERN.test(current.code)
+ ) {
+ return current as PostgresErrorLike;
+ }
+
+ current = (current as { cause?: unknown }).cause;
+ }
+};
+
+export const createDatabaseErrorRef = (): string =>
+ `${DATABASE_ERROR_REF_PREFIX}${randomUUID().replaceAll('-', '').slice(0, 12)}`;
+
+/**
+ * A one-line index (no SQL, no bound values) plus the error itself. The full
+ * error is kept on purpose β€” the client only gets the reference, so the log is
+ * the only place the statement and driver diagnostics still exist. Logging both
+ * here rather than relying on the route's `onError` also covers callers that
+ * never go through an HTTP handler (server-side `createCallerFactory` calls).
+ */
+const logDatabaseError = (entry: DatabaseErrorLogEntry) => {
+ const fields = [`ref=${entry.ref}`, `sqlstate=${entry.sqlstate ?? 'unknown'}`];
+ if (entry.constraint) fields.push(`constraint=${entry.constraint}`);
+ if (entry.table) fields.push(`table=${entry.table}`);
+ if (entry.column) fields.push(`column=${entry.column}`);
+
+ console.error(`[db-error] ${fields.join(' ')}`);
+ console.error(`[db-error] ${entry.ref} original`, entry.error);
+};
+
+/**
+ * Replace a database failure's client-facing message with a neutral one that
+ * carries a searchable reference, and keep the failure itself in the server
+ * log under that same reference.
+ *
+ * Returns `undefined` for anything that is not a leaked query, so unrelated
+ * 500s keep their original (already-meaningful) message. Codes routers chose
+ * deliberately are respected for the same reason as `toUpstreamTRPCError`.
+ */
+export const toDatabaseTRPCError = (
+ error: TRPCError,
+ options: ToDatabaseTRPCErrorOptions = {},
+): TRPCError | undefined => {
+ // Respect codes routers chose deliberately; only reclassify the generic 500.
+ if (error.code !== 'INTERNAL_SERVER_ERROR') return;
+
+ let current: unknown = error;
+ let leaked: DrizzleQueryErrorLike | undefined;
+
+ for (let depth = 0; current && depth <= MAX_CAUSE_DEPTH; depth++) {
+ if (isDrizzleQueryError(current)) {
+ leaked = current;
+ break;
+ }
+
+ current = (current as { cause?: unknown }).cause;
+ }
+
+ // Also cover the case where the wrapper survived as the top-level message but
+ // the object was flattened somewhere in transit.
+ const leaksQuery =
+ !!leaked || (typeof error.message === 'string' && error.message.startsWith('Failed query:'));
+
+ if (!leaksQuery) return;
+
+ const ref = (options.createRef ?? createDatabaseErrorRef)();
+ const postgres = findPostgresError(leaked ?? error.cause ?? error);
+
+ (options.log ?? logDatabaseError)({
+ column: postgres?.column,
+ constraint: postgres?.constraint,
+ error,
+ ref,
+ sqlstate: postgres?.code,
+ table: postgres?.table,
+ });
+
+ // Keep the original as `cause`: tRPC's clients and our own error logger both
+ // walk the chain, so the statement stays reachable from the error object.
+ return new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: `Internal server error (ref: ${ref})`,
+ });
+};
+
+/**
+ * Keep Drizzle's SQL dump out of the client response: the user gets a neutral
+ * message plus a reference, the server log keeps the whole error.
+ */
+export const databaseError = trpc.middleware(async ({ next }) => {
+ const result = await next();
+ if (result.ok) return result;
+
+ const mapped = toDatabaseTRPCError(result.error);
+ if (mapped) throw mapped;
+
+ return result;
+});
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index 709a84fd9d3..af9802da31d 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -49,6 +49,7 @@ import {
getConversationChatInputUiState,
getConversationSendButtonProps,
toChatInputMessages,
+ toDisplayableSendErrorMessage,
} from './utils';
import {
canSendVoiceMessage,
@@ -270,6 +271,22 @@ const ChatInput = memo<ChatInputProps>(
const sendMessageErrorMsg = useConversationStore(messageStateSelectors.sendMessageError);
const clearSendMessageError = useChatStore((s) => s.clearSendMessageError);
+ // `inputSendErrorMsg` is the failed call's `error.message` verbatim, so it
+ // can still be a raw database dump on servers predating the databaseError
+ // middleware. That text is SQL plus every bound parameter β€” including the
+ // user's own input β€” so it is never echoed; generic copy stands in for it.
+ const sendMessageErrorTitle = useMemo(
+ () =>
+ sendMessageErrorMsg
+ ? t('input.errorMsg', {
+ errorMsg:
+ toDisplayableSendErrorMessage(sendMessageErrorMsg) ??
+ t('unknownError', { ns: 'common' }),
+ })
+ : undefined,
+ [sendMessageErrorMsg, t],
+ );
+
// File store - for UI state only (disabled button, etc.)
const fileList = useFileStore(fileChatSelectors.chatUploadFileList);
const contextList = useFileStore(fileChatSelectors.chatContextSelections(contextKey));
@@ -452,11 +469,11 @@ const ChatInput = memo<ChatInputProps>(
{/* Keep the chat input mounted while an intervention panel is showing β€”
unmounting would wipe the Lexical editor's in-memory document. */}
<div style={{ display: hasPendingInterventions ? 'none' : 'contents' }}>
- {sendMessageErrorMsg && (
+ {sendMessageErrorTitle && (
<Flexbox paddingBlock={'0 6px'} paddingInline={12}>
<Alert
closable
- title={t('input.errorMsg', { errorMsg: sendMessageErrorMsg })}
+ title={sendMessageErrorTitle}
type={'secondary'}
onClose={clearSendMessageError}
/>
diff --git a/src/features/Conversation/ChatInput/utils.test.ts b/src/features/Conversation/ChatInput/utils.test.ts
index 4f45a8c3f42..c5d1c0c2f76 100644
--- a/src/features/Conversation/ChatInput/utils.test.ts
+++ b/src/features/Conversation/ChatInput/utils.test.ts
@@ -7,6 +7,7 @@ import {
getConversationChatInputUiState,
getConversationSendButtonProps,
toChatInputMessages,
+ toDisplayableSendErrorMessage,
} from './utils';
const tokenMessages = [
@@ -238,3 +239,38 @@ describe('getConversationChatInputUiState', () => {
});
});
});
+
+describe('toDisplayableSendErrorMessage', () => {
+ /**
+ * @example A send fails before the server's databaseError middleware strips it.
+ */
+ it('drops a raw database error instead of showing SQL and its bound values', () => {
+ // ROOT CAUSE:
+ //
+ // `inputSendErrorMsg` is the failed call's `error.message` verbatim. Drizzle
+ // stringifies a failed statement as `Failed query: <sql>\nparams: <values>`,
+ // so this notice used to render the whole INSERT together with every bound
+ // parameter β€” including the user's own message text β€” with no way for the
+ // user to act on it.
+ //
+ // Before: the raw dump was rendered as-is.
+ // After: the caller substitutes localized generic copy.
+ const raw =
+ 'Failed query: insert into "messages" ("id", "role", "content") values ($1, $2, $3)\n' +
+ 'params: msg_1,user,a user message';
+
+ expect(toDisplayableSendErrorMessage(raw)).toBeUndefined();
+ });
+
+ it('keeps a message the user can act on', () => {
+ expect(toDisplayableSendErrorMessage('Internal server error (ref: db_abc123def456)')).toBe(
+ 'Internal server error (ref: db_abc123def456)',
+ );
+ });
+
+ it('trims surrounding whitespace and treats blank input as nothing to show', () => {
+ expect(toDisplayableSendErrorMessage(' Network error ')).toBe('Network error');
+ expect(toDisplayableSendErrorMessage(' ')).toBeUndefined();
+ expect(toDisplayableSendErrorMessage()).toBeUndefined();
+ });
+});
diff --git a/src/features/Conversation/ChatInput/utils.ts b/src/features/Conversation/ChatInput/utils.ts
index 2de00a83618..d74bbe7006c 100644
--- a/src/features/Conversation/ChatInput/utils.ts
+++ b/src/features/Conversation/ChatInput/utils.ts
@@ -3,6 +3,7 @@ import type { OpenAIChatMessage, UIChatMessage } from '@lobechat/types';
import type { PlaceholderVariant } from '@/features/ChatInput/InputEditor/Placeholder';
import type { SendButtonProps } from '@/features/ChatInput/store/initialState';
import { chatHelpers } from '@/store/chat/helpers';
+import { isMachineErrorMessage } from '@/utils/machineErrorMessage';
type SupportedChatInputRole = Extract<OpenAIChatMessage['role'], 'assistant' | 'tool' | 'user'>;
@@ -121,3 +122,26 @@ export const getConversationChatInputUiState = ({
showStopButton: isInputLoading,
};
};
+
+/**
+ * Resolve the text the send-failure notice should show for a raw error message.
+ *
+ * Use when:
+ * - Rendering `inputSendErrorMsg`, which is the failed call's message verbatim.
+ * On any surface that does not go through the server's `databaseError`
+ * middleware it can still be Drizzle's `Failed query: <sql>` / `params:
+ * <values>` dump β€” the whole statement plus every bound parameter, including
+ * the user's own message body.
+ *
+ * Returns:
+ * - The message to display, or `undefined` when the caller must substitute its
+ * own localized copy β€” i.e. the raw message was machine output, not a
+ * sentence written for the person.
+ */
+export const toDisplayableSendErrorMessage = (message?: string): string | undefined => {
+ const trimmed = message?.trim();
+ if (!trimmed) return undefined;
+ if (isMachineErrorMessage(trimmed)) return undefined;
+
+ return trimmed;
+};
diff --git a/src/features/EnvironmentManager/errorMessage.ts b/src/features/EnvironmentManager/errorMessage.ts
index 6ef99899a08..5f1a994ee05 100644
--- a/src/features/EnvironmentManager/errorMessage.ts
+++ b/src/features/EnvironmentManager/errorMessage.ts
@@ -1,3 +1,5 @@
+import { isMachineErrorMessage } from '@/utils/machineErrorMessage';
+
/**
* What a failed environment action should say to the person.
*
@@ -27,24 +29,6 @@ const CODE_KEYS: Record<string, string> = {
*/
const isUntranslatedCode = (message: string): boolean => /^[A-Z][\dA-Z_]{2,}$/.test(message);
-/**
- * A message the server never wrote for anyone to read.
- *
- * Drizzle raises a failed insert with the whole statement and its parameters in
- * `message`, and tRPC forwards that verbatim, so a missing column surfaced in a
- * dialog as a screenful of SQL β€” with the row's values in it. Anything of that
- * shape is dropped in favour of the caller's own line, which at least says
- * which action failed.
- *
- * Matched narrowly on purpose. The fallthrough below exists so that refusals
- * written as sentences still reach the person, and widening this to "anything
- * long" would swallow those too.
- */
-const isMachineMessage = (message: string): boolean =>
- message.startsWith('Failed query:') ||
- // A stack trace that came along for the ride.
- /\n\s+at\s/.test(message);
-
const readIssues = (message: string): string[] | undefined => {
if (!message.startsWith('[')) return;
try {
@@ -72,7 +56,7 @@ export const describeError = (
const key = CODE_KEYS[message];
if (key) return t(key);
- if (isMachineMessage(message) || isUntranslatedCode(message)) return fallback;
+ if (isMachineErrorMessage(message) || isUntranslatedCode(message)) return fallback;
const issues = readIssues(message);
if (issues) {
diff --git a/src/utils/machineErrorMessage.test.ts b/src/utils/machineErrorMessage.test.ts
new file mode 100644
index 00000000000..74ae1742113
--- /dev/null
+++ b/src/utils/machineErrorMessage.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+
+import { isMachineErrorMessage } from './machineErrorMessage';
+
+describe('isMachineErrorMessage', () => {
+ it('recognises a Drizzle query dump', () => {
+ expect(
+ isMachineErrorMessage(
+ 'Failed query: insert into "messages" ("id") values ($1)\nparams: msg_1',
+ ),
+ ).toBe(true);
+ });
+
+ it('recognises an error carrying its stack trace', () => {
+ expect(isMachineErrorMessage('could not delete\n at Object.<anonymous>')).toBe(true);
+ });
+
+ it('leaves a sentence the server wrote on purpose alone', () => {
+ expect(isMachineErrorMessage('The folder is not empty')).toBe(false);
+ expect(isMachineErrorMessage('could not delete')).toBe(false);
+ });
+});
diff --git a/src/utils/machineErrorMessage.ts b/src/utils/machineErrorMessage.ts
new file mode 100644
index 00000000000..76ae41f3160
--- /dev/null
+++ b/src/utils/machineErrorMessage.ts
@@ -0,0 +1,18 @@
+/**
+ * A message the server never wrote for anyone to read.
+ *
+ * Drizzle raises a failed statement with the whole query and its bound
+ * parameters in `message` (`Failed query: <sql>` / `params: <values>`), and
+ * tRPC forwards that verbatim; a stack trace can tag along the same way.
+ * Neither is something a person can act on β€” and the bound values can carry
+ * their own input back at them β€” so callers drop them in favour of their own
+ * copy for the action that failed.
+ *
+ * Matched narrowly on purpose. Refusals the server *did* write as sentences
+ * must still reach the person, so "anything long" or "anything with a newline"
+ * is not a signal.
+ */
+export const isMachineErrorMessage = (message: string): boolean =>
+ message.startsWith('Failed query:') ||
+ // A stack trace that came along for the ride.
+ /\n\s+at\s/.test(message);