Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(toolbar): report a real error when heatmap capture fails (#88229)

posthog[bot]6658c9dd8688
diff --git a/frontend/src/toolbar/index.tsx b/frontend/src/toolbar/index.tsx
index 674ee13e9643..0c78fc7bc31d 100644
--- a/frontend/src/toolbar/index.tsx
+++ b/frontend/src/toolbar/index.tsx
@@ -19,7 +19,7 @@ import { isToolbarMounted, posthogToolbarController, setToolbarRefs } from '~/to
import { toolbarLogger } from '~/toolbar/toolbarLogger'
import { captureToolbarException } from '~/toolbar/toolbarPosthogJS'
import { isToolbarRequestError } from '~/toolbar/toolbarRequestError'
-import { safeFetch } from '~/toolbar/utils'
+import { safeFetch, toError } from '~/toolbar/utils'
import { ToolbarParams } from '~/types'
interface InitKeaProps {
@@ -55,7 +55,10 @@ const initKeaInToolbar = ({ routerHistory, routerLocation, beforePlugins }: Init
// expected request failures (4xx/5xx/network) - those are logged above but
// must not pollute error tracking. Anything else is a genuine toolbar bug.
if (!isToolbarRequestError(error)) {
- captureToolbarException(error, 'kea_loader', {
+ // A loader can reject with a non-Error value (e.g. html-to-image throws a raw
+ // DOM Event). Normalize first so no bare value reaches error tracking without a
+ // message or stack, whatever a loader throws.
+ captureToolbarException(toError(error), 'kea_loader', {
reducer_key: reducerKey,
action_key: actionKey,
})
diff --git a/frontend/src/toolbar/utils.test.ts b/frontend/src/toolbar/utils.test.ts
index 53907fb42c6d..e57873f5e3b9 100644
--- a/frontend/src/toolbar/utils.test.ts
+++ b/frontend/src/toolbar/utils.test.ts
@@ -4,6 +4,7 @@ import {
elementToQuery,
joinWithUiHost,
safeFetch,
+ toError,
unescapeCssSelector,
} from './utils'
@@ -201,4 +202,27 @@ describe('utils', () => {
}
)
})
+
+ describe('toError', () => {
+ it('returns an existing Error unchanged', () => {
+ const original = new TypeError('boom')
+ expect(toError(original)).toBe(original)
+ })
+
+ it('wraps a raw DOM Event in a real Error that keeps its type', () => {
+ // html-to-image rejects with an Event when a page resource fails to load. Without
+ // this, posthog-js files an exception with no message and no stack.
+ const result = toError(new Event('error'), 'Failed to capture screenshot of html')
+ expect(result).toBeInstanceOf(Error)
+ expect(result.message).toBe('Failed to capture screenshot of html (threw Event)')
+ })
+
+ it.each([
+ { input: null, type: 'null' },
+ { input: 'oops', type: 'string' },
+ { input: 42, type: 'number' },
+ ])('names the original type of $input', ({ input, type }) => {
+ expect(toError(input).message).toBe(`Non-Error value thrown (${type})`)
+ })
+ })
})
diff --git a/frontend/src/toolbar/utils.ts b/frontend/src/toolbar/utils.ts
index 8e3bdf611df0..fec5520a3c61 100644
--- a/frontend/src/toolbar/utils.ts
+++ b/frontend/src/toolbar/utils.ts
@@ -18,6 +18,25 @@ export const TOOLBAR_ID = '__POSTHOG_TOOLBAR__'
// load-bearing at runtime — verify before storing strings that flow into auth headers.
export const asNonEmptyString = (v: unknown): string | null => (typeof v === 'string' && v.length > 0 ? v : null)
+// Third-party code on the customer page can reject with a non-Error value. html-to-image, for
+// example, rejects with a raw DOM Event when a page resource fails to load. posthog-js serializes
+// such a value into an exception with no message and no stack, so error tracking cannot triage it.
+// Return real Errors unchanged; wrap anything else in an Error that keeps the original type.
+export function toError(value: unknown, context?: string): Error {
+ if (value instanceof Error) {
+ return value
+ }
+ const type =
+ value === null
+ ? 'null'
+ : typeof value === 'object'
+ ? ((value as { constructor?: { name?: string } }).constructor?.name ?? 'object')
+ : typeof value
+ const error = new Error(context ? `${context} (threw ${type})` : `Non-Error value thrown (${type})`)
+ error.name = 'NonError'
+ return error
+}
+
// `fetch` that always resolves to something safe to read `.status`/`.ok`/`.json()` off. A
// site-level `window.fetch` wrapper on the customer page can resolve to `undefined`/`null` (or
// another non-object), which makes every downstream `.status` access throw a TypeError. Normalize
diff --git a/frontend/src/toolbar/utils/screenshot.test.ts b/frontend/src/toolbar/utils/screenshot.test.ts
new file mode 100644
index 000000000000..309c27042268
--- /dev/null
+++ b/frontend/src/toolbar/utils/screenshot.test.ts
@@ -0,0 +1,40 @@
+import { toBlob } from 'html-to-image'
+
+import { captureElementScreenshot } from '~/toolbar/utils/screenshot'
+
+jest.mock('html-to-image', () => ({
+ toBlob: jest.fn(),
+}))
+
+const mockToBlob = toBlob as jest.Mock
+
+describe('captureElementScreenshot', () => {
+ beforeEach(() => mockToBlob.mockReset())
+
+ it('rethrows a raw DOM Event rejection as a real Error with the element and original type', async () => {
+ // html-to-image rejects with an Event, not an Error, when a page resource fails to load.
+ // A bare Event reaches error tracking with no message and no stack.
+ mockToBlob.mockRejectedValueOnce(new Event('error'))
+ const element = document.createElement('img')
+ element.id = 'logo'
+
+ await expect(captureElementScreenshot(element)).rejects.toThrow(
+ 'Failed to capture screenshot of img#logo (threw Event)'
+ )
+ })
+
+ it('throws a real Error when toBlob resolves to null', async () => {
+ mockToBlob.mockResolvedValueOnce(null)
+
+ await expect(captureElementScreenshot(document.documentElement)).rejects.toThrow(
+ 'Rendering the element to an image produced no data'
+ )
+ })
+
+ it('returns the blob on success', async () => {
+ const blob = new Blob(['x'], { type: 'image/jpeg' })
+ mockToBlob.mockResolvedValueOnce(blob)
+
+ await expect(captureElementScreenshot(document.documentElement)).resolves.toBe(blob)
+ })
+})
diff --git a/frontend/src/toolbar/utils/screenshot.ts b/frontend/src/toolbar/utils/screenshot.ts
index 656c583d818d..b35570c626a4 100644
--- a/frontend/src/toolbar/utils/screenshot.ts
+++ b/frontend/src/toolbar/utils/screenshot.ts
@@ -1,7 +1,7 @@
import { captureElementImage } from 'lib/utils/captureElementImage'
import { toolbarUploadMedia } from '~/toolbar/toolbarFetch'
-import { TOOLBAR_ID } from '~/toolbar/utils'
+import { TOOLBAR_ID, toError } from '~/toolbar/utils'
export interface ElementScreenshot {
mediaId: string
@@ -18,13 +18,23 @@ export interface CaptureOptions {
backgroundColor?: string
}
+function describeElement(element: HTMLElement): string {
+ return `${element.tagName.toLowerCase()}${element.id ? `#${element.id}` : ''}`
+}
+
export async function captureElementScreenshot(element: HTMLElement, options?: CaptureOptions): Promise<Blob> {
- return captureElementImage(element, {
- type: 'image/jpeg',
- quality: 0.7,
- filter: screenshotFilter,
- ...options,
- })
+ try {
+ return await captureElementImage(element, {
+ type: 'image/jpeg',
+ quality: 0.7,
+ filter: screenshotFilter,
+ ...options,
+ })
+ } catch (error) {
+ // html-to-image rejects with a raw DOM Event when a resource on the page fails to load.
+ // Rethrow a real Error so the failure reaches error tracking with a message and a stack.
+ throw toError(error, `Failed to capture screenshot of ${describeElement(element)}`)
+ }
}
export async function uploadScreenshot(blob: Blob): Promise<ElementScreenshot> {