Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(observability): add reportError capture seam (LFE-10974) (#15278)

Nikita Kabardin2be9a252b8e4
diff --git a/web/src/utils/captureUnknownError.ts b/web/src/utils/captureUnknownError.ts
index 33ea767bae..8f1e2a0ee6 100644
--- a/web/src/utils/captureUnknownError.ts
+++ b/web/src/utils/captureUnknownError.ts
@@ -1,72 +1,28 @@
-import { captureException } from "@sentry/nextjs";
-
-/**
- * Turn an unknown thrown/logged value into a legible string.
- *
- * `String(value)` and template interpolation collapse most objects to the
- * useless `[object Object]` / `[object ErrorEvent]`. We try `JSON.stringify`
- * first, and when that yields nothing useful — `"{}"` for objects whose fields
- * live on the prototype (DOM `Event`s, `DOMException`), or a throw on circular
- * references — we fall back to a descriptor built from the value's constructor
- * name and own enumerable keys.
- */
-function safeStringify(value: unknown): string {
- try {
- const json = JSON.stringify(value);
- if (json !== undefined && json !== "{}") {
- return json;
- }
- } catch {
- // circular reference or a throwing getter — fall through to describe()
- }
- return describeUnknown(value);
-}
-
-function describeUnknown(value: unknown): string {
- if (value === null) return "null";
- if (typeof value !== "object") return String(value);
- const ctorName =
- (value as { constructor?: { name?: string } }).constructor?.name ??
- "Object";
- const keys = Object.keys(value as Record<string, unknown>);
- return keys.length > 0 ? `${ctorName} { ${keys.join(", ")} }` : ctorName;
-}
+import { reportError } from "@/src/utils/reportError";
/**
* Report an unknown (possibly non-Error) value to Sentry as a legible Error.
*
- * `instrumentation-client.ts` enables
- * `captureConsoleIntegration({ levels: ["error"] })`, so every
- * `console.error(nonError)` also becomes an opaque Sentry event
- * (`[object Object]` / "Object captured as exception with keys …"). Route
- * caught-unknown values through here instead: real `Error`s pass through
- * untouched (stack preserved); anything else is synthesized into an `Error`
- * with a readable message. We log with `console.warn` (not `console.error`) so
- * the integration does not double-capture the same failure.
+ * Thin wrapper over the {@link reportError} seam kept for its existing call
+ * sites (playground/auth). It maps the legacy `(context, value, extra)` shape
+ * onto `reportError`, which owns the single unknown→`Error` coercion and the
+ * single `captureException` path:
+ * - real `Error`s pass through untouched (stack preserved);
+ * - anything else is synthesized into an `Error` with a readable `[context]`
+ * message (never `[object Object]` / `[object ErrorEvent]`);
+ * - it tags `area: context` and logs via `console.warn` (not `console.error`,
+ * which `captureConsoleIntegration` would double-capture).
+ *
+ * `context` is also mirrored into `extra` to preserve the exact payload legacy
+ * callers have always sent. Prefer `reportError` directly in new code.
*/
export function captureUnknownError(
context: string,
value: unknown,
extra?: Record<string, unknown>,
): void {
- const err =
- value instanceof Error
- ? value
- : new Error(
- `[${context}] ${
- typeof value === "string" ? value : safeStringify(value)
- }`,
- );
- captureException(err, {
+ reportError(value, {
+ area: context,
extra: { context, ...extra },
- tags: { area: context },
});
- // warn, not error → captureConsoleIntegration only captures console.error,
- // so this line does not create a second, opaque Sentry event. The
- // synthesized (non-Error) message already carries the `[context]` prefix; a
- // pass-through Error does not, so add it here only in that branch to keep the
- // context present exactly once in both cases.
- console.warn(
- value instanceof Error ? `[${context}] ${err.message}` : err.message,
- );
}
diff --git a/web/src/utils/reportError.clienttest.ts b/web/src/utils/reportError.clienttest.ts
new file mode 100644
index 0000000000..ee2ae291da
--- /dev/null
+++ b/web/src/utils/reportError.clienttest.ts
@@ -0,0 +1,110 @@
+import { reportError } from "@/src/utils/reportError";
+
+const { captureExceptionMock, addBreadcrumbMock } = vi.hoisted(() => ({
+ captureExceptionMock: vi.fn(),
+ addBreadcrumbMock: vi.fn(),
+}));
+
+vi.mock("@sentry/nextjs", () => ({
+ captureException: captureExceptionMock,
+ addBreadcrumb: addBreadcrumbMock,
+}));
+
+describe("reportError", () => {
+ let warnSpy: ReturnType<typeof vi.spyOn>;
+ let errorSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ captureExceptionMock.mockClear();
+ addBreadcrumbMock.mockClear();
+ warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ warnSpy.mockRestore();
+ errorSpy.mockRestore();
+ });
+
+ describe("expected: true", () => {
+ it("adds a breadcrumb and does NOT capture", () => {
+ reportError(new Error("member of another project"), {
+ area: "trpc.query",
+ expected: true,
+ extra: { code: "FORBIDDEN" },
+ });
+
+ expect(captureExceptionMock).not.toHaveBeenCalled();
+ expect(addBreadcrumbMock).toHaveBeenCalledTimes(1);
+ const crumb = addBreadcrumbMock.mock.calls[0]![0];
+ expect(crumb.category).toBe("trpc.query");
+ expect(crumb.type).toBe("error");
+ expect(crumb.level).toBe("info");
+ expect(crumb.data).toEqual({ code: "FORBIDDEN" });
+ });
+
+ it("does not warn or error for an expected state", () => {
+ reportError("some expected state", {
+ area: "auth.session",
+ expected: true,
+ });
+
+ expect(warnSpy).not.toHaveBeenCalled();
+ expect(errorSpy).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("unexpected (captured)", () => {
+ it("passes a real Error through untouched (same instance → stack preserved) with area tag", () => {
+ const original = new Error("boom");
+ reportError(original, { area: "io.parse", extra: { traceId: "abc" } });
+
+ expect(captureExceptionMock).toHaveBeenCalledTimes(1);
+ const [err, options] = captureExceptionMock.mock.calls[0]!;
+ expect(err).toBe(original); // same instance → original stack preserved
+ expect(options.tags.area).toBe("io.parse");
+ expect(options.extra).toEqual({ traceId: "abc" });
+ expect(addBreadcrumbMock).not.toHaveBeenCalled();
+ });
+
+ it("synthesizes a legible Error for a plain object (not [object Object])", () => {
+ reportError({ code: 42, reason: "bad" }, { area: "io.parse" });
+
+ expect(captureExceptionMock).toHaveBeenCalledTimes(1);
+ const [err] = captureExceptionMock.mock.calls[0]!;
+ expect(err).toBeInstanceOf(Error);
+ expect(err.message).not.toContain("[object Object]");
+ expect(err.message).toContain("code");
+ expect(err.message).toContain("42");
+ expect(err.message).toContain("io.parse");
+ });
+
+ it("synthesizes a legible Error for a string", () => {
+ reportError("something failed", { area: "io.parse" });
+
+ const [err] = captureExceptionMock.mock.calls[0]!;
+ expect(err).toBeInstanceOf(Error);
+ expect(err.message).toBe("[io.parse] something failed");
+ });
+
+ it("logs via console.warn, never console.error (avoids captureConsole double-capture)", () => {
+ reportError(new Error("boom"), { area: "io.parse" });
+
+ expect(warnSpy).toHaveBeenCalledTimes(1);
+ expect(errorSpy).not.toHaveBeenCalled();
+ });
+
+ it("captures exactly once per call", () => {
+ reportError(new Error("once"), { area: "io.parse" });
+ expect(captureExceptionMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("passes undefined extra through when omitted", () => {
+ reportError(new Error("boom"), { area: "io.parse" });
+
+ const [, options] = captureExceptionMock.mock.calls[0]!;
+ expect(options.tags.area).toBe("io.parse");
+ expect(options.extra).toBeUndefined();
+ });
+ });
+});
diff --git a/web/src/utils/reportError.ts b/web/src/utils/reportError.ts
new file mode 100644
index 0000000000..3f729d3d80
--- /dev/null
+++ b/web/src/utils/reportError.ts
@@ -0,0 +1,108 @@
+import { addBreadcrumb, captureException } from "@sentry/nextjs";
+
+/**
+ * Turn an unknown thrown/logged value into a legible string.
+ *
+ * `String(value)` and template interpolation collapse most objects to the
+ * useless `[object Object]` / `[object ErrorEvent]`. We try `JSON.stringify`
+ * first, and when that yields nothing useful — `"{}"` for objects whose fields
+ * live on the prototype (DOM `Event`s, `DOMException`), or a throw on circular
+ * references — we fall back to a descriptor built from the value's constructor
+ * name and own enumerable keys.
+ */
+function safeStringify(value: unknown): string {
+ try {
+ const json = JSON.stringify(value);
+ if (json !== undefined && json !== "{}") {
+ return json;
+ }
+ } catch {
+ // circular reference or a throwing getter — fall through to describe()
+ }
+ return describeUnknown(value);
+}
+
+function describeUnknown(value: unknown): string {
+ if (value === null) return "null";
+ if (typeof value !== "object") return String(value);
+ const ctorName =
+ (value as { constructor?: { name?: string } }).constructor?.name ??
+ "Object";
+ const keys = Object.keys(value as Record<string, unknown>);
+ return keys.length > 0 ? `${ctorName} { ${keys.join(", ")} }` : ctorName;
+}
+
+/**
+ * Coerce any caught/unknown value into a legible real `Error`.
+ *
+ * This is the single unknown→`Error` coercion in the client codebase; both the
+ * generic {@link reportError} seam and the legacy `captureUnknownError` helper
+ * route through it. Real `Error`s pass through untouched so Sentry keeps the
+ * original stack; anything else is synthesized into an `Error` whose message is
+ * `[area] <readable value>` (never `[object Object]`), so the synthesized event
+ * both groups by `area` and stays diagnosable.
+ */
+export function coerceToError(area: string, value: unknown): Error {
+ return value instanceof Error
+ ? value
+ : new Error(
+ `[${area}] ${typeof value === "string" ? value : safeStringify(value)}`,
+ );
+}
+
+/**
+ * The single capture seam every future client error-report routes through.
+ *
+ * Why a seam: classification and tagging live in one place, so Sentry's
+ * `beforeSend` in `instrumentation-client.ts` can be a backstop rather than the
+ * strategy. Report through here instead of calling `captureException` directly.
+ *
+ * Behavior:
+ * - `expected: true` — the failure is the product working as designed (a state
+ * the UI already renders: a missing/forbidden resource, invalid user input, an
+ * offline/transport blip the server already owns). We do NOT capture — an event
+ * in Sentry is a promise a human should act, and nobody acts on an expected
+ * state. We drop a breadcrumb so the (unexpected) error that DOES get captured
+ * later in the session still carries the trail of what happened before it.
+ * - 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`.
+ *
+ * `console.warn`, never `console.error`: `instrumentation-client.ts` enables
+ * `captureConsoleIntegration({ levels: ["error"] })`, so a `console.error` here
+ * would mint a second, opaque Sentry event for the same failure.
+ *
+ * PII: keep the message static and legible and never route user content
+ * (prompt/trace text, tokens, ids, share-link secrets) through it — a message
+ * that interpolates user data both leaks and shatters Sentry grouping. Keeping
+ * `extra` free of PII is the caller's responsibility; this seam does not scrub it.
+ */
+export function reportError(
+ error: unknown,
+ opts: { area: string; expected?: boolean; extra?: Record<string, unknown> },
+): void {
+ if (opts.expected === true) {
+ addBreadcrumb({
+ category: opts.area,
+ type: "error",
+ level: "info",
+ message: "Expected error (not captured)",
+ data: { ...opts.extra },
+ });
+ return;
+ }
+
+ const err = coerceToError(opts.area, error);
+ captureException(err, {
+ 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.
+ console.warn(
+ error instanceof Error ? `[${opts.area}] ${err.message}` : err.message,
+ );
+}