Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

refactor(web): one seam owns error capture β€” migrate raw captureException sites to reportError + lint enforcement (#15781)

Nikita Kabardinfbc170eec10e
diff --git a/web/eslint.config.mjs b/web/eslint.config.mjs
index ea74532d49..5d692c7aa8 100644
--- a/web/eslint.config.mjs
+++ b/web/eslint.config.mjs
@@ -5,6 +5,51 @@ import eslintPluginTailwindcss from "eslint-plugin-tailwindcss";
import nextConfig from "@repo/eslint-config/next";
+// Restricted import patterns that apply everywhere. Flat config replaces (not
+// merges) a rule that is configured twice, so every block that configures
+// no-restricted-imports must spread the full pattern list it wants.
+const restrictedImportPatterns = [
+ {
+ regex: "^react-icons$",
+ message:
+ "Only react-icons/si and react-icons/tb are allowed. Please use lucide-react for other icons.",
+ },
+ {
+ regex: "^react-icons/(?!si(?:/|$)|tb(?:/|$)).*",
+ message:
+ "Only react-icons/si and react-icons/tb are allowed. Please use lucide-react for other icons.",
+ },
+ {
+ // Relative paths escaping web/ bypass @langfuse/shared's exports
+ // map (which points at dist/) and pull shared *source* into the
+ // Next.js typecheck program, where web's next-auth augmentation
+ // breaks it β€” this failed production deploys (PR #15031).
+ // Note: only static imports are checked. Dynamic import() is not
+ // covered by this rule, which also leaves room for the one
+ // legitimate use: tests that need a Vite-transformed source copy
+ // of a shared module to observe env mutations (vitest loads the
+ // CJS dist through Node's require cache as a second instance β€”
+ // see blob-storage-integration-trpc.servertest.ts).
+ regex: "^(\\.\\./)+(packages|ee|worker)/",
+ message:
+ "Do not import other workspace packages via relative paths. Use the package entrypoints instead (e.g. @langfuse/shared/src/db, @langfuse/shared/src/server).",
+ },
+];
+
+// One seam owns error capture: raw Sentry capture APIs are restricted to the
+// reportError seam (src/utils/reportError.ts) so classification (`expected`),
+// `area` tagging, and non-Error coercion live in exactly one place. The
+// capture contract lives in the seam's doc comment and in
+// .agents/skills/sentry-instrumentation/SKILL.md (human-facing version:
+// web/OBSERVABILITY.md, landing separately). Exempted files get a dedicated
+// config block below without this pattern β€” never an inline eslint-disable.
+const sentryCapturePattern = {
+ regex: "^@sentry/nextjs$",
+ importNames: ["captureException", "captureMessage"],
+ message:
+ "Do not capture directly β€” route through the reportError seam (@/src/utils/reportError) or a helper that wraps it (captureUnknownError, reportParserWorkerError), so one seam owns error classification. See the reportError doc comment and .agents/skills/sentry-instrumentation/SKILL.md.",
+};
+
// eslint-plugin-tailwindcss types this as Config | ConfigArray, but the
// recommended export is a single flat config object with rules at runtime.
const tailwindcssRecommendedConfig =
@@ -207,42 +252,31 @@ export default [
},
},
- // Restricted import paths. Flat config replaces (not merges) a rule that is
- // configured twice, so all no-restricted-imports patterns live in this one
- // block.
+ // Restricted import paths (patterns defined at the top of this file).
{
name: "langfuse/web/restricted-imports",
rules: {
"no-restricted-imports": [
"error",
{
- patterns: [
- {
- regex: "^react-icons$",
- message:
- "Only react-icons/si and react-icons/tb are allowed. Please use lucide-react for other icons.",
- },
- {
- regex: "^react-icons/(?!si(?:/|$)|tb(?:/|$)).*",
- message:
- "Only react-icons/si and react-icons/tb are allowed. Please use lucide-react for other icons.",
- },
- {
- // Relative paths escaping web/ bypass @langfuse/shared's exports
- // map (which points at dist/) and pull shared *source* into the
- // Next.js typecheck program, where web's next-auth augmentation
- // breaks it β€” this failed production deploys (PR #15031).
- // Note: only static imports are checked. Dynamic import() is not
- // covered by this rule, which also leaves room for the one
- // legitimate use: tests that need a Vite-transformed source copy
- // of a shared module to observe env mutations (vitest loads the
- // CJS dist through Node's require cache as a second instance β€”
- // see blob-storage-integration-trpc.servertest.ts).
- regex: "^(\\.\\./)+(packages|ee|worker)/",
- message:
- "Do not import other workspace packages via relative paths. Use the package entrypoints instead (e.g. @langfuse/shared/src/db, @langfuse/shared/src/server).",
- },
- ],
+ patterns: [...restrictedImportPatterns, sentryCapturePattern],
+ },
+ ],
+ },
+ },
+
+ // Sanctioned homes for raw Sentry capture APIs: the reportError seam itself
+ // and the SDK init (`import * as Sentry` would otherwise trip the
+ // importNames restriction). Last-match wins in flat config, so these files
+ // get the shared restrictions without the Sentry capture pattern.
+ {
+ name: "langfuse/web/restricted-imports-sentry-seam",
+ files: ["src/utils/reportError.ts", "instrumentation-client.ts"],
+ rules: {
+ "no-restricted-imports": [
+ "error",
+ {
+ patterns: restrictedImportPatterns,
},
],
},
diff --git a/web/src/components/error-page.tsx b/web/src/components/error-page.tsx
index 345bcf3a24..ae80e12ec6 100644
--- a/web/src/components/error-page.tsx
+++ b/web/src/components/error-page.tsx
@@ -4,7 +4,7 @@ import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
import { useEffect } from "react";
import Link from "next/link";
-import { captureException } from "@sentry/nextjs";
+import { reportError } from "@/src/utils/reportError";
import { stripBasePath } from "@/src/utils/redirect";
export const ErrorPage = ({
@@ -82,8 +82,9 @@ export const ErrorPageWithSentry = ({
useEffect(() => {
// Capture the error with Sentry
if (window !== undefined)
- captureException(
+ reportError(
new Error(`ErrorPageWithSentry rendered: ${title}, ${message}`),
+ { area: "error-page" },
);
}, [title, message]); // Empty dependency array means this effect runs once on mount
diff --git a/web/src/hooks/parserWorkerError.clienttest.ts b/web/src/hooks/parserWorkerError.clienttest.ts
index 837672c2c0..385af3a787 100644
--- a/web/src/hooks/parserWorkerError.clienttest.ts
+++ b/web/src/hooks/parserWorkerError.clienttest.ts
@@ -1,11 +1,13 @@
import { reportParserWorkerError } from "@/src/hooks/parserWorkerError";
-import { captureException } from "@sentry/nextjs";
-vi.mock("@sentry/nextjs", () => ({
- captureException: vi.fn(),
+const { mockCaptureException } = vi.hoisted(() => ({
+ mockCaptureException: vi.fn(),
}));
-const mockCaptureException = vi.mocked(captureException);
+vi.mock("@sentry/nextjs", () => ({
+ captureException: mockCaptureException,
+ addBreadcrumb: vi.fn(),
+}));
/**
* Observability contract for the JSON-parser Web Worker `onerror` path
@@ -37,7 +39,7 @@ describe("reportParserWorkerError", () => {
reportParserWorkerError("useParsedTrace", event);
expect(mockCaptureException).toHaveBeenCalledTimes(1);
- const [err, opts] = mockCaptureException.mock.calls[0];
+ const [err, opts] = mockCaptureException.mock.calls[0]!;
expect(err).toBeInstanceOf(Error);
expect((err as Error).message).toContain(
"[useParsedTrace] worker failed to load",
@@ -65,33 +67,55 @@ describe("reportParserWorkerError", () => {
);
expect(mockCaptureException).toHaveBeenCalledTimes(1);
- expect(mockCaptureException.mock.calls[0][0]).toBe(real);
+ expect(mockCaptureException.mock.calls[0]![0]).toBe(real);
});
it("logs a readable string via console.warn, not console.error (no double-capture)", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const error = vi.spyOn(console, "error").mockImplementation(() => {});
- reportParserWorkerError("useParsedTrace", makeErrorEvent());
+ const event = makeErrorEvent();
+ reportParserWorkerError("useParsedTrace", event);
// console.error would be re-captured by captureConsoleIntegration.
expect(error).not.toHaveBeenCalled();
expect(warn).toHaveBeenCalledTimes(1);
- const logged = String(warn.mock.calls[0][0]);
- expect(logged).toContain("[useParsedTrace] Worker failed to load");
+ const logged = String(warn.mock.calls[0]![0]);
+ // hookName + location details appear exactly once, prefixed by the area.
+ expect(logged).toContain(
+ "[io-parse-worker] useParsedTrace worker failed to load",
+ );
+ expect(logged).toContain(event.filename);
+ expect(logged).not.toContain("[useParsedTrace]"); // no double-bracketed hook
expect(logged).not.toContain("[object ErrorEvent]");
warn.mockRestore();
error.mockRestore();
});
+ it("keeps hookName + details on the console line when a real event.error passes through", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+
+ const event = makeErrorEvent({ error: new Error("worker init threw") });
+ reportParserWorkerError("useParsedObservation", event);
+
+ expect(warn).toHaveBeenCalledTimes(1);
+ const logged = String(warn.mock.calls[0]![0]);
+ expect(logged).toContain(
+ "[io-parse-worker] useParsedObservation worker failed to load",
+ );
+ expect(logged).toContain(event.filename);
+
+ warn.mockRestore();
+ });
+
it("degrades gracefully when ErrorEvent fields are empty", () => {
reportParserWorkerError(
"useParsedTrace",
makeErrorEvent({ message: "", filename: "" }),
);
- const [err] = mockCaptureException.mock.calls[0];
+ const [err] = mockCaptureException.mock.calls[0]!;
expect((err as Error).message).toContain("unknown");
expect((err as Error).message).toContain("?");
});
diff --git a/web/src/hooks/parserWorkerError.ts b/web/src/hooks/parserWorkerError.ts
index 6e8b3a99af..b6657a71e0 100644
--- a/web/src/hooks/parserWorkerError.ts
+++ b/web/src/hooks/parserWorkerError.ts
@@ -1,4 +1,4 @@
-import { captureException } from "@sentry/nextjs";
+import { reportError } from "@/src/utils/reportError";
/**
* Turn a JSON-parser Web Worker `onerror` ErrorEvent into a legible,
@@ -11,9 +11,10 @@ import { captureException } from "@sentry/nextjs";
* "[object ErrorEvent]", discarding message/filename/lineno and making the
* resulting issues undiagnosable.
*
- * This extracts the real fields, captures one proper Error with structured
- * context, and logs a readable string via `console.warn` (NOT `console.error`,
- * so captureConsoleIntegration β€” which captures the "error" level β€” does not
+ * This extracts the real fields and reports one proper Error with structured
+ * context through the {@link reportError} seam, which tags `area` and logs the
+ * companion line via `console.warn` (NOT `console.error`, so
+ * captureConsoleIntegration β€” which captures the "error" level β€” does not
* double-capture a second, opaque event for the same failure).
*
* Note: in-worker parse failures are a separate, already-legible path β€” they
@@ -33,7 +34,8 @@ export function reportParserWorkerError(
? event.error
: new Error(`[${hookName}] worker failed to load: ${details}`);
- captureException(realError, {
+ reportError(realError, {
+ area: "io-parse-worker",
extra: {
workerHook: hookName,
message: event.message,
@@ -41,10 +43,10 @@ export function reportParserWorkerError(
lineno: event.lineno,
colno: event.colno,
},
- tags: { area: "io-parse-worker" },
+ // Companion console line: carry hookName + location details exactly once
+ // in both branches β€” the pass-through Error's message lacks them, the
+ // synthesized one already embeds them. Console-only; the captured event
+ // is the Error above.
+ warnMessage: `${hookName} worker failed to load: ${details}`,
});
-
- // console.warn (not console.error) keeps the console legible without
- // triggering a duplicate capture via captureConsoleIntegration.
- console.warn(`[${hookName}] Worker failed to load: ${details}`);
}
diff --git a/web/src/pages/auth/sign-in.tsx b/web/src/pages/auth/sign-in.tsx
index 68f25e909b..e9cfc9e4d2 100644
--- a/web/src/pages/auth/sign-in.tsx
+++ b/web/src/pages/auth/sign-in.tsx
@@ -38,7 +38,7 @@ import { isAnySsoConfigured } from "@/src/ee/features/multi-tenant-sso/utils";
import { isEmailVerificationRequired } from "@/src/features/auth-credentials/lib/credentialsUtils";
import { Code, Key } from "lucide-react";
import { useRouter } from "next/router";
-import { captureException } from "@sentry/nextjs";
+import { reportError } from "@/src/utils/reportError";
import { captureUnknownError } from "@/src/utils/captureUnknownError";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import useLocalStorage from "@/src/components/useLocalStorage";
@@ -572,7 +572,9 @@ export default function SignIn({
!nextAuthErrorDescription &&
!signInErrors.find((e) => e.code === nextAuthError)
) {
- captureException(new Error(`Sign in error: ${nextAuthError}`));
+ reportError(new Error(`Sign in error: ${nextAuthError}`), {
+ area: "auth.signIn",
+ });
}
}, [nextAuthError, nextAuthErrorDescription]);
@@ -635,13 +637,16 @@ export default function SignIn({
});
if (result === undefined) {
setCredentialsFormError("An unexpected error occurred.");
- captureException(new Error("Sign in result is undefined"));
+ reportError(new Error("Sign in result is undefined"), {
+ area: "auth.signIn.credentials",
+ });
} else if (!result.ok) {
if (!result.error) {
- captureException(
+ reportError(
new Error(
`Sign in result error is falsy, result: ${JSON.stringify(result)}`,
),
+ { area: "auth.signIn.credentials" },
);
}
setCredentialsFormError(
diff --git a/web/src/utils/api.ts b/web/src/utils/api.ts
index c9fedcfd27..9d842a8c0f 100644
--- a/web/src/utils/api.ts
+++ b/web/src/utils/api.ts
@@ -5,7 +5,7 @@
* We also create a few inference helpers for input and output types.
*/
-import { addBreadcrumb, captureException } from "@sentry/nextjs";
+import { addBreadcrumb } from "@sentry/nextjs";
import {
createTRPCProxyClient,
httpBatchLink,
@@ -26,6 +26,7 @@ import { env } from "@/src/env.mjs";
import { showVersionUpdateToast } from "@/src/features/notifications/showVersionUpdateToast";
import { versionUpdateStore } from "@/src/features/version-update/versionUpdateStore";
import { type AppRouter } from "@/src/server/api/root";
+import { reportError } from "@/src/utils/reportError";
import { setUpSuperjson } from "@/src/utils/superjson";
import { trpcErrorToast } from "@/src/utils/trpcErrorToast";
@@ -355,9 +356,10 @@ const handleTrpcError = (error: unknown, shouldSilenceError = false) => {
},
});
} else {
- // Real tRPC errors keep flowing to Sentry, now tagged by procedure/code
+ // Real tRPC errors keep flowing to Sentry, tagged by procedure/code
// so they group and route instead of collapsing into one opaque bucket.
- captureException(error, {
+ reportError(error, {
+ area: "trpc",
tags: {
"trpc.code": getTrpcErrorCode(error),
"trpc.path": getTrpcErrorPath(error),
@@ -365,8 +367,8 @@ const handleTrpcError = (error: unknown, shouldSilenceError = false) => {
});
}
} else {
- // For non-TRPC errors, still send to Sentry
- captureException(error);
+ // For non-TRPC errors, still send to Sentry (coerced to a real Error).
+ reportError(error, { area: "trpc" });
}
if (!shouldSilenceError && shouldShowToast(error)) {
@@ -505,7 +507,7 @@ export const api = createTRPCNext<AppRouter>({
requestTooLargeDiagnosticsLink(),
loggerLink({
// Only enable in development - production logs would be captured by Sentry
- // in an unreadable format. We handle 5xx errors via captureException() in
+ // in an unreadable format. We handle 5xx errors via reportError in
// handleTrpcError and use DataDog for additional server-side logging.
enabled: () => process.env.NODE_ENV === "development",
}),
@@ -593,7 +595,7 @@ export const directApi = createTRPCProxyClient<AppRouter>({
links: [
loggerLink({
// Only enable in development - production logs would be captured by Sentry
- // in an unreadable format. We handle 5xx errors via captureException() in
+ // in an unreadable format. We handle 5xx errors via reportError in
// handleTrpcError and use DataDog for additional server-side logging.
enabled: () => process.env.NODE_ENV === "development",
}),
diff --git a/web/src/utils/reportError.clienttest.ts b/web/src/utils/reportError.clienttest.ts
index ee2ae291da..d4164d5d28 100644
--- a/web/src/utils/reportError.clienttest.ts
+++ b/web/src/utils/reportError.clienttest.ts
@@ -106,5 +106,56 @@ describe("reportError", () => {
expect(options.tags.area).toBe("io.parse");
expect(options.extra).toBeUndefined();
});
+
+ it("merges caller tags alongside the area tag", () => {
+ reportError(new Error("boom"), {
+ area: "trpc",
+ tags: {
+ "trpc.code": "INTERNAL_SERVER_ERROR",
+ "trpc.path": "traces.all",
+ },
+ });
+
+ const [, options] = captureExceptionMock.mock.calls[0]!;
+ expect(options.tags).toEqual({
+ "trpc.code": "INTERNAL_SERVER_ERROR",
+ "trpc.path": "traces.all",
+ area: "trpc",
+ });
+ });
+
+ it("the seam's area tag wins over a conflicting caller tag", () => {
+ reportError(new Error("boom"), {
+ area: "trpc",
+ tags: { area: "spoofed" },
+ });
+
+ const [, options] = captureExceptionMock.mock.calls[0]!;
+ expect(options.tags.area).toBe("trpc");
+ });
+
+ it("warnMessage overrides the console line body, prefixed with the area", () => {
+ reportError(new Error("boom"), {
+ area: "io-parse-worker",
+ warnMessage: "useParsedTrace worker failed to load: details",
+ });
+
+ expect(warnSpy).toHaveBeenCalledTimes(1);
+ expect(warnSpy.mock.calls[0]![0]).toBe(
+ "[io-parse-worker] useParsedTrace worker failed to load: details",
+ );
+ });
+
+ it("warnMessage never affects what is captured", () => {
+ const original = new Error("boom");
+ reportError(original, {
+ area: "io-parse-worker",
+ warnMessage: "console-only text",
+ });
+
+ const [err] = captureExceptionMock.mock.calls[0]!;
+ expect(err).toBe(original);
+ expect(err.message).toBe("boom");
+ });
});
});
diff --git a/web/src/utils/reportError.ts b/web/src/utils/reportError.ts
index 3f729d3d80..cdcc063b11 100644
--- a/web/src/utils/reportError.ts
+++ b/web/src/utils/reportError.ts
@@ -67,6 +67,12 @@ export function coerceToError(area: string, value: unknown): Error {
* - otherwise β€” coerce to a real `Error` (see {@link coerceToError}),
* `captureException` with an `area` tag (so issues route/group by surface) and
* the caller's structured `extra`, then log a companion `console.warn`.
+ * Optional `tags` add further Sentry tags (e.g. `trpc.code`); on a key
+ * conflict the seam's `area` tag wins. Optional `warnMessage` overrides the
+ * companion console line's body (always prefixed with `[area]`) for callers
+ * whose legible console text differs from the captured Error's message β€”
+ * e.g. a pass-through Error that lacks the caller's context. It never
+ * affects what is captured.
*
* `console.warn`, never `console.error`: `instrumentation-client.ts` enables
* `captureConsoleIntegration({ levels: ["error"] })`, so a `console.error` here
@@ -79,7 +85,13 @@ export function coerceToError(area: string, value: unknown): Error {
*/
export function reportError(
error: unknown,
- opts: { area: string; expected?: boolean; extra?: Record<string, unknown> },
+ opts: {
+ area: string;
+ expected?: boolean;
+ extra?: Record<string, unknown>;
+ tags?: Record<string, string | undefined>;
+ warnMessage?: string;
+ },
): void {
if (opts.expected === true) {
addBreadcrumb({
@@ -94,15 +106,20 @@ export function reportError(
const err = coerceToError(opts.area, error);
captureException(err, {
- tags: { area: opts.area },
+ tags: { ...opts.tags, area: opts.area },
extra: opts.extra,
});
// warn, not error β†’ captureConsoleIntegration only captures console.error, so
// this line does not create a second, opaque event. Show the `area` exactly
- // once: a synthesized error already embeds `[area]` in its message
- // (coerceToError), a pass-through real Error does not β€” so prefix only that
- // branch to keep the surface legible in the console without duplicating it.
+ // once: a `warnMessage` body gets the prefix; without one, a synthesized
+ // error already embeds `[area]` in its message (coerceToError) while a
+ // pass-through real Error does not β€” so prefix only that branch to keep the
+ // surface legible in the console without duplicating it.
console.warn(
- error instanceof Error ? `[${opts.area}] ${err.message}` : err.message,
+ opts.warnMessage !== undefined
+ ? `[${opts.area}] ${opts.warnMessage}`
+ : error instanceof Error
+ ? `[${opts.area}] ${err.message}`
+ : err.message,
);
}