🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
refactor(trpc): share onError logger across lambda/mobile/tools routes (#17213)
Tsuki85e2eac19218
diff --git a/apps/server/src/routers/lambda/aiChat.ts b/apps/server/src/routers/lambda/aiChat.tsindex 03e643b8332..cd4248e869a 100644--- a/apps/server/src/routers/lambda/aiChat.ts+++ b/apps/server/src/routers/lambda/aiChat.ts@@ -19,6 +19,7 @@ import { ThreadModel } from '@/database/models/thread';import { TopicModel } from '@/database/models/topic';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { markSilentTRPCErrorLog } from '@/libs/trpc/utils/errorLogger';import { resolveContext } from '@/server/routers/lambda/_helpers/resolveContext';import { AiChatService } from '@/server/services/aiChat';import { AiGenerationService } from '@/server/services/aiGeneration';@@ -29,8 +30,6 @@ const log = debug('lobe-lambda-router:ai-chat');const { createPrefixedTimingContext, logTiming, runTimedStage } = createTimingHelpers('lobe-server:chat:lobehub:timing',);-const SILENT_TRPC_ERROR_LOG_KEY = '__lobeSilentTRPCErrorLog';-type TRPCErrorCode = ConstructorParameters<typeof TRPCError>[0]['code'];type TRPCStatusCode = Parameters<typeof getStatusKeyFromCode>[0];@@ -51,19 +50,6 @@ const getTRPCErrorCodeFromStatus = (status: number): TRPCErrorCode => {return 'INTERNAL_SERVER_ERROR';};-const markSilentTRPCErrorLog = (error: unknown) => {- if (!error || typeof error !== 'object') return;-- try {- Object.defineProperty(error, SILENT_TRPC_ERROR_LOG_KEY, {- configurable: true,- value: true,- });- } catch {- // Best-effort logging hint; never let it mask the original runtime error.- }-};-const createRuntimeTRPCError = (error: unknown,options?: { silentHandlerLog?: boolean },diff --git a/packages/trpc/src/utils/errorLogger.test.ts b/packages/trpc/src/utils/errorLogger.test.tsnew file mode 100644index 00000000000..7ba03973541--- /dev/null+++ b/packages/trpc/src/utils/errorLogger.test.ts@@ -0,0 +1,49 @@+import { TRPCError } from '@trpc/server';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createTRPCErrorLogger, markSilentTRPCErrorLog } from './errorLogger';++describe('createTRPCErrorLogger', () => {+ beforeEach(() => {+ vi.spyOn(console, 'info').mockImplementation(() => {});+ vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('logs errors with the endpoint scope', () => {+ const onError = createTRPCErrorLogger('mobile');+ const error = new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: 'boom' });++ onError({ error, path: 'aiChat.outputJSON', type: 'mutation' });++ expect(console.info).toHaveBeenCalledWith(+ 'Error in tRPC handler (mobile) on path: aiChat.outputJSON, type: mutation',+ );+ expect(console.error).toHaveBeenCalledWith(error);+ });++ it('skips UNAUTHORIZED errors', () => {+ const onError = createTRPCErrorLogger('lambda');+ const error = new TRPCError({ code: 'UNAUTHORIZED' });++ onError({ error, path: 'session.getSessions', type: 'query' });++ expect(console.info).not.toHaveBeenCalled();+ expect(console.error).not.toHaveBeenCalled();+ });++ it('skips errors whose cause was marked via markSilentTRPCErrorLog', () => {+ const onError = createTRPCErrorLogger('lambda');+ const cause = new Error('rate limited');+ markSilentTRPCErrorLog(cause);+ const error = new TRPCError({ cause, code: 'TOO_MANY_REQUESTS', message: 'rate limited' });++ onError({ error, path: 'aiChat.outputJSON', type: 'mutation' });++ expect(console.info).not.toHaveBeenCalled();+ expect(console.error).not.toHaveBeenCalled();+ });+});diff --git a/packages/trpc/src/utils/errorLogger.ts b/packages/trpc/src/utils/errorLogger.tsnew file mode 100644index 00000000000..94f9ffbc6e3--- /dev/null+++ b/packages/trpc/src/utils/errorLogger.ts@@ -0,0 +1,52 @@+import type { TRPCError } from '@trpc/server';++/**+ * Routers can stamp this key on `error.cause` to tell the HTTP handler to+ * skip logging the error — used for expected user-channel 4xx failures+ * (e.g. input-completion provider rejections) that would otherwise pollute+ * error monitoring. Write it via `markSilentTRPCErrorLog` below; this file+ * is the single home for both halves of the contract.+ */+export const SILENT_TRPC_ERROR_LOG_KEY = '__lobeSilentTRPCErrorLog';++/**+ * Stamp the silent-log marker on an error so `createTRPCErrorLogger` skips+ * it. Best-effort: never throws, so it can't mask the original error.+ */+export const markSilentTRPCErrorLog = (error: unknown) => {+ if (!error || typeof error !== 'object') return;++ try {+ Object.defineProperty(error, SILENT_TRPC_ERROR_LOG_KEY, {+ configurable: true,+ value: true,+ });+ } catch {+ // Best-effort logging hint; never let it mask the original runtime error.+ }+};++const shouldSkipTRPCErrorLog = (cause: unknown): boolean =>+ Boolean(+ cause &&+ typeof cause === 'object' &&+ (cause as Record<string, unknown>)[SILENT_TRPC_ERROR_LOG_KEY],+ );++/**+ * Shared `onError` for tRPC fetch handlers. Skips UNAUTHORIZED (normal+ * client behavior — the frontend prompts the user to log in) and+ * silent-marked errors, so every user-facing endpoint applies the same log+ * hygiene. Used by the lambda / mobile / tools routes; the async route+ * intentionally keeps its own handler (background jobs have no user to+ * prompt, so UNAUTHORIZED there is a real anomaly worth logging).+ */+export const createTRPCErrorLogger =+ (endpoint: string) =>+ ({ error, path, type }: { error: TRPCError; path?: string; type: string }) => {+ if (error.code === 'UNAUTHORIZED') return;+ if (shouldSkipTRPCErrorLog(error.cause)) return;++ console.info(`Error in tRPC handler (${endpoint}) on path: ${path}, type: ${type}`);+ console.error(error);+ };diff --git a/src/app/(backend)/trpc/lambda/[trpc]/route.ts b/src/app/(backend)/trpc/lambda/[trpc]/route.tsindex ebb39a0efbc..26839f4d4c6 100644--- a/src/app/(backend)/trpc/lambda/[trpc]/route.ts+++ b/src/app/(backend)/trpc/lambda/[trpc]/route.ts@@ -2,19 +2,11 @@ import { fetchRequestHandler } from '@trpc/server/adapters/fetch';import { type NextRequest } from 'next/server';import { createLambdaContext } from '@/libs/trpc/lambda/context';+import { createTRPCErrorLogger } from '@/libs/trpc/utils/errorLogger';import { prepareRequestForTRPC } from '@/libs/trpc/utils/request-adapter';import { createResponseMeta } from '@/libs/trpc/utils/responseMeta';import { lambdaRouter } from '@/server/routers/lambda';-const SILENT_TRPC_ERROR_LOG_KEY = '__lobeSilentTRPCErrorLog';--const shouldSkipTRPCErrorLog = (cause: unknown): boolean =>- Boolean(- cause &&- typeof cause === 'object' &&- (cause as Record<string, unknown>)[SILENT_TRPC_ERROR_LOG_KEY],- );-const handler = (req: NextRequest) => {// Clone the request to avoid "Response body object should not be disturbed or locked" error// in Next.js 16 when the body stream has been consumed by Next.js internal mechanisms@@ -28,15 +20,7 @@ const handler = (req: NextRequest) => {endpoint: '/trpc/lambda',- onError: ({ error, path, type }) => {- // Filter out the error of UNAUTHORIZED, because this is normal behavior- // And it has been displayed at the front end to let the user login- if (error.code === 'UNAUTHORIZED') return;- if (shouldSkipTRPCErrorLog(error.cause)) return;-- console.info(`Error in tRPC handler (lambda) on path: ${path}, type: ${type}`);- console.error(error);- },+ onError: createTRPCErrorLogger('lambda'),req: preparedReq,responseMeta: createResponseMeta,diff --git a/src/app/(backend)/trpc/mobile/[trpc]/route.ts b/src/app/(backend)/trpc/mobile/[trpc]/route.tsindex dc9465a6435..43a5b720282 100644--- a/src/app/(backend)/trpc/mobile/[trpc]/route.ts+++ b/src/app/(backend)/trpc/mobile/[trpc]/route.ts@@ -2,6 +2,7 @@ import { fetchRequestHandler } from '@trpc/server/adapters/fetch';import { type NextRequest } from 'next/server';import { createLambdaContext } from '@/libs/trpc/lambda/context';+import { createTRPCErrorLogger } from '@/libs/trpc/utils/errorLogger';import { prepareRequestForTRPC } from '@/libs/trpc/utils/request-adapter';import { createResponseMeta } from '@/libs/trpc/utils/responseMeta';import { mobileRouter } from '@/server/routers/mobile';@@ -19,10 +20,7 @@ const handler = (req: NextRequest) => {endpoint: '/trpc/mobile',- onError: ({ error, path, type }) => {- console.info(`Error in tRPC handler (mobile) on path: ${path}, type: ${type}`);- console.error(error);- },+ onError: createTRPCErrorLogger('mobile'),req: preparedReq,responseMeta: createResponseMeta,diff --git a/src/app/(backend)/trpc/tools/[trpc]/route.ts b/src/app/(backend)/trpc/tools/[trpc]/route.tsindex 1f33d86d8d7..8842e794e45 100644--- a/src/app/(backend)/trpc/tools/[trpc]/route.ts+++ b/src/app/(backend)/trpc/tools/[trpc]/route.ts@@ -2,6 +2,7 @@ import { fetchRequestHandler } from '@trpc/server/adapters/fetch';import { type NextRequest } from 'next/server';import { createLambdaContext } from '@/libs/trpc/lambda/context';+import { createTRPCErrorLogger } from '@/libs/trpc/utils/errorLogger';import { prepareRequestForTRPC } from '@/libs/trpc/utils/request-adapter';import { createResponseMeta } from '@/libs/trpc/utils/responseMeta';import { toolsRouter } from '@/server/routers/tools';@@ -19,10 +20,7 @@ const handler = (req: NextRequest) => {endpoint: '/trpc/tools',- onError: ({ error, path, type }) => {- console.error(`Error in tRPC handler (tools) on path: ${path}, type: ${type}`);- console.error(error);- },+ onError: createTRPCErrorLogger('tools'),req: preparedReq,responseMeta: createResponseMeta,