: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(toolbar): never report request-shaped failures to error tracking (#70318)
Rafael Audibertdc291ae920a5
diff --git a/.semgrep/rules/devex/toolbar-no-capture-on-request-failure.test.ts b/.semgrep/rules/devex/toolbar-no-capture-on-request-failure.test.tsnew file mode 100644index 000000000000..63d3905c716b--- /dev/null+++ b/.semgrep/rules/devex/toolbar-no-capture-on-request-failure.test.ts@@ -0,0 +1,37 @@+// @ts-nocheck+// Test fixture for the toolbar-no-capture-on-request-failure rule.++function badNegatedBranch(result) {+ // ruleid: toolbar-no-capture-on-request-failure+ if (!result.ok) {+ toolbarLogger.error('api', 'failed')+ captureToolbarException(new Error(result.error.detail), 'load_actions')+ return []+ }+}++function badElseBranch(result) {+ // ruleid: toolbar-no-capture-on-request-failure+ if (result.ok) {+ return result.data+ } else {+ captureToolbarException(new Error(result.error.detail), 'load_actions')+ return []+ }+}++function okTaggedThrow(result) {+ // ok: toolbar-no-capture-on-request-failure+ if (!result.ok) {+ throw new ToolbarRequestError(result.error.detail, result.status)+ }+ return result.data+}++function okLocalFallback(result) {+ // ok: toolbar-no-capture-on-request-failure+ if (!result.ok) {+ return []+ }+ return result.data.results+}diff --git a/.semgrep/rules/devex/toolbar-no-capture-on-request-failure.yaml b/.semgrep/rules/devex/toolbar-no-capture-on-request-failure.yamlnew file mode 100644index 000000000000..98001c81ccb7--- /dev/null+++ b/.semgrep/rules/devex/toolbar-no-capture-on-request-failure.yaml@@ -0,0 +1,33 @@+rules:+ - id: toolbar-no-capture-on-request-failure+ message: |+ `captureToolbarException` inside a failed-request branch. A `!result.ok` from+ `toolbarApi` is an expected outcome (auth expiry, validation, backend incident,+ network) - it is already logged and visible in telemetry, and must not be+ reported to error tracking. Handle the failure locally (fallback value, toast+ via `toastOnError`) or `throw new ToolbarRequestError(...)` if a kea `*Failure`+ action needs to fire. Error tracking is reserved for genuine toolbar bugs.+ severity: ERROR+ languages: [typescript]+ paths:+ include:+ - frontend/src/toolbar+ - frontend/src/lib/components/heatmaps+ - frontend/src/lib/components/HedgehogMode+ pattern-either:+ - pattern: |+ if (!$RESULT.ok) {+ ...+ captureToolbarException(...)+ ...+ }+ - pattern: |+ if ($RESULT.ok) {+ ...+ } else {+ ...+ captureToolbarException(...)+ ...+ }+ metadata:+ category: best-practicediff --git a/.semgrep/rules/devex/toolbar-no-raw-fetch.test.ts b/.semgrep/rules/devex/toolbar-no-raw-fetch.test.tsnew file mode 100644index 000000000000..e05e56191855--- /dev/null+++ b/.semgrep/rules/devex/toolbar-no-raw-fetch.test.ts@@ -0,0 +1,26 @@+// @ts-nocheck+// Test fixture for the toolbar-no-raw-fetch rule.++// ruleid: toolbar-no-raw-fetch+const a = await fetch('/api/projects/@current/actions/')++// ruleid: toolbar-no-raw-fetch+const b = await fetch(url, { method: 'POST', body: JSON.stringify(payload) })++// ruleid: toolbar-no-raw-fetch+void fetch(`${host}/toolbar_oauth/check`, { method: 'HEAD' })++// ruleid: toolbar-no-raw-fetch+const c = await window.fetch(url)++// ruleid: toolbar-no-raw-fetch+const d = await globalThis.fetch(url)++// ok: toolbar-no-raw-fetch+const e = await safeFetch(url, { credentials: 'include' })++// ok: toolbar-no-raw-fetch+const f = await toolbarFetch('/api/projects/@current/actions/', 'GET')++// ok: toolbar-no-raw-fetch+const g = await toolbarApi.actions.list({ context: 'load_actions' })diff --git a/.semgrep/rules/devex/toolbar-no-raw-fetch.yaml b/.semgrep/rules/devex/toolbar-no-raw-fetch.yamlnew file mode 100644index 000000000000..dfcea2680604--- /dev/null+++ b/.semgrep/rules/devex/toolbar-no-raw-fetch.yaml@@ -0,0 +1,34 @@+rules:+ - id: toolbar-no-raw-fetch+ message: |+ Raw `fetch(...)` in toolbar code. The toolbar runs on customer pages, where+ `window.fetch` may be replaced by wrappers that resolve to non-Response values,+ and where network failures (offline, ad blockers, CORS, CSP) are everyday+ outcomes - not bugs. A raw fetch bypasses the layer that normalizes those+ failures and keeps them out of error tracking.++ Use, in order of preference:+ • `toolbarApi` (`~/toolbar/toolbarApi`) for authenticated API requests - it+ returns a `ToolbarApiResult` union and never throws+ • `toolbarFetch` (`~/toolbar/toolbarFetch`) only when you need the raw+ `Response` and cannot use `toolbarApi`+ • `safeFetch` (`~/toolbar/utils`) for unauthenticated requests (auth flows,+ preloads, local blob URLs)++ If a raw fetch is genuinely unavoidable (e.g. a circular import), add+ `// nosemgrep: toolbar-no-raw-fetch` with a short reason and make sure a+ rejection can never escape unhandled.+ severity: ERROR+ languages: [typescript]+ paths:+ include:+ - frontend/src/toolbar+ exclude:+ - '**/*.test.ts'+ - '**/*.test.tsx'+ pattern-either:+ - pattern: fetch(...)+ - pattern: window.fetch(...)+ - pattern: globalThis.fetch(...)+ metadata:+ category: best-practicediff --git a/.semgrep/rules/devex/toolbar-transport-no-error-tracking.test.ts b/.semgrep/rules/devex/toolbar-transport-no-error-tracking.test.tsnew file mode 100644index 000000000000..18baebfc7bcf--- /dev/null+++ b/.semgrep/rules/devex/toolbar-transport-no-error-tracking.test.ts@@ -0,0 +1,14 @@+// @ts-nocheck+// Test fixture for the toolbar-transport-no-error-tracking rule.++// ruleid: toolbar-transport-no-error-tracking+captureToolbarException(error, 'network', { status: 0 })++// ruleid: toolbar-transport-no-error-tracking+toolbarPosthogJS.captureException(error, { toolbar_context: 'api' })++// ok: toolbar-transport-no-error-tracking+toolbarLogger.error('api', 'Request failed (network)', { context })++// ok: toolbar-transport-no-error-tracking+toolbarPosthogJS.capture('toolbar api request', { status: 0 })diff --git a/.semgrep/rules/devex/toolbar-transport-no-error-tracking.yaml b/.semgrep/rules/devex/toolbar-transport-no-error-tracking.yamlnew file mode 100644index 000000000000..420bb29c60c4--- /dev/null+++ b/.semgrep/rules/devex/toolbar-transport-no-error-tracking.yaml@@ -0,0 +1,23 @@+rules:+ - id: toolbar-transport-no-error-tracking+ message: |+ Exception capture in the toolbar's transport layer. `toolbarFetch` and+ `toolbarApi` must never report failures to error tracking: every failure they+ see is request-shaped (4xx, 5xx, network, malformed body) and expected on+ customer pages. They log via `toolbarLogger`, emit `toolbar api request`+ telemetry, and return a failure result (`ToolbarApiResult` / a synthetic+ `Response`) for the caller to handle. If a call site needs to raise, it throws+ `ToolbarRequestError`, which the global kea loader handler logs without+ capturing. Error tracking is reserved for genuine toolbar bugs, reported from+ the code that owns them.+ severity: ERROR+ languages: [typescript]+ paths:+ include:+ - frontend/src/toolbar/toolbarApi.ts+ - frontend/src/toolbar/toolbarFetch.ts+ pattern-either:+ - pattern: captureToolbarException(...)+ - pattern: $X.captureException(...)+ metadata:+ category: best-practicediff --git a/frontend/src/lib/components/HedgehogMode/hedgehogModeLogic.ts b/frontend/src/lib/components/HedgehogMode/hedgehogModeLogic.tsindex 67ca489f3e62..7316a94960db 100644--- a/frontend/src/lib/components/HedgehogMode/hedgehogModeLogic.ts+++ b/frontend/src/lib/components/HedgehogMode/hedgehogModeLogic.ts@@ -55,11 +55,21 @@ export const hedgehogModeLogic = kea<hedgehogModeLogicType>([const endpoint = '/api/users/@me/hedgehog_config'const mountedToolbarConfigLogic = toolbarConfigLogic.findMounted()if (mountedToolbarConfigLogic) {- // If toolbarConfigLogic is mounted, we're inside the Toolbar+ // If toolbarConfigLogic is mounted, we're inside the Toolbar.if (!mountedToolbarConfigLogic.values.isAuthenticated) {return null}- return await (await toolbarFetch(endpoint, 'GET')).json()+ // The config is cosmetic - on any request failure (network, auth,+ // non-JSON body) fall back to defaults rather than raising an error.+ try {+ const response = await toolbarFetch(endpoint, 'GET')+ if (!response.ok) {+ return null+ }+ return await response.json()+ } catch {+ return null+ }}return await api.get<Partial<HedgehogConfig>>(endpoint)},diff --git a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts b/frontend/src/lib/components/heatmaps/heatmapDataLogic.tsindex f6e5944e8ba2..101ac5be65d3 100644--- a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts+++ b/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts@@ -27,6 +27,7 @@ import { getAppContext } from 'lib/utils/getAppContext'import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'import { toolbarFetch } from '~/toolbar/toolbarFetch'+import { ToolbarRequestError } from '~/toolbar/toolbarRequestError'import { HeatmapElement, HeatmapResponseType } from '~/toolbar/types'import { FilterType } from '~/types'@@ -67,6 +68,46 @@ export interface HeatmapDataLogicProps {exportToken?: string | null}+/**+ * Fetch a heatmap endpoint and raise request failures the right way for each context:+ * in the toolbar a failed request is an expected outcome, so it becomes a tagged+ * `ToolbarRequestError` (drives the loader's *Failure action without being reported to+ * error tracking); in-app the pre-existing plain-error behavior is preserved.+ */+async function fetchHeatmapData(+ props: HeatmapDataLogicProps,+ apiURL: string,+ options: { authenticateOn403?: boolean } = {}+): Promise<Response> {+ let response: Response+ try {+ response = await (props.context === 'toolbar'+ ? toolbarFetch(apiURL, 'GET')+ : props.exportToken+ ? fetch(apiURL, { headers: { Authorization: `Bearer ${props.exportToken}` } })+ : fetch(apiURL))+ } catch (e) {+ if (props.context === 'toolbar') {+ throw new ToolbarRequestError('Network error while loading heatmap data')+ }+ throw e+ }++ if (props.context === 'toolbar' && response.status === 403 && options.authenticateOn403) {+ toolbarConfigLogic.actions.authenticate()+ }++ if (response.status !== 200) {+ const message = await parseHeatmapErrorMessage(response)+ if (props.context === 'toolbar') {+ throw new ToolbarRequestError(message, response.status)+ }+ throw new Error(message)+ }++ return response+}+export function heatmapApiPath(context: HeatmapDataLogicProps['context'], endpoint: '' | 'events/'): string {if (context === 'in-app') {// The unscoped /api/heatmap/ route resolves the team from the user's *global* current@@ -267,21 +308,9 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([)}`// if we export the heatmap, we need to add the export token to the headers- const response = await (props.context === 'toolbar'- ? toolbarFetch(apiURL, 'GET')- : props.exportToken- ? fetch(apiURL, { headers: { Authorization: `Bearer ${props.exportToken}` } })- : fetch(apiURL))+ const response = await fetchHeatmapData(props, apiURL, { authenticateOn403: true })breakpoint()- if (props.context === 'toolbar' && response.status === 403) {- toolbarConfigLogic.actions.authenticate()- }-- if (response.status !== 200) {- throw new Error(await parseHeatmapErrorMessage(response))- }-const data = await response.json()actions.setIsReady(true)return data@@ -318,17 +347,9 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>(['?')}`- const response = await (props.context === 'toolbar'- ? toolbarFetch(apiURL, 'GET')- : props.exportToken- ? fetch(apiURL, { headers: { Authorization: `Bearer ${props.exportToken}` } })- : fetch(apiURL))+ const response = await fetchHeatmapData(props, apiURL)breakpoint()- if (response.status !== 200) {- throw new Error(await parseHeatmapErrorMessage(response))- }-return await response.json()},},@@ -532,14 +553,11 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>(['?')}`- const response = await (props.context === 'toolbar'- ? toolbarFetch(apiURL, 'GET')- : props.exportToken- ? fetch(apiURL, { headers: { Authorization: `Bearer ${props.exportToken}` } })- : fetch(apiURL))-- if (response.status !== 200) {- lemonToast.error(await parseHeatmapErrorMessage(response))+ let response: Response+ try {+ response = await fetchHeatmapData(props, apiURL)+ } catch (e) {+ lemonToast.error(e instanceof Error ? e.message : 'Failed to load more events')return}diff --git a/frontend/src/toolbar/ToolbarApp.tsx b/frontend/src/toolbar/ToolbarApp.tsxindex 8a57b3601e2d..c9b20a20d994 100644--- a/frontend/src/toolbar/ToolbarApp.tsx+++ b/frontend/src/toolbar/ToolbarApp.tsx@@ -9,7 +9,7 @@ import { useSecondRender } from 'lib/hooks/useSecondRender'import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'import { ToolbarContainer } from '~/toolbar/ToolbarContainer'import { toolbarLogger } from '~/toolbar/toolbarLogger'-import { captureToolbarException, toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'+import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'import { ToolbarProps } from '~/types'import { TOOLBAR_ID } from './utils'@@ -64,15 +64,13 @@ export function ToolbarApp(props: ToolbarProps = {}): JSX.Element {styleLink.onload = () => setDidLoadStyles(true)// Without onerror the toolbar silently stays invisible when the// CSS 404s (didLoadStyles never flips to true). That masks- // misconfigured apiHost / rejected URLs. Surface the failure- // via logger + telemetry and render the toolbar anyway —- // missing styles is a worse UX than nothing.+ // misconfigured apiHost / rejected URLs. A failed stylesheet+ // request is expected on customer pages (ad blockers, offline,+ // misconfigured hosts), so surface it via logger + telemetry -+ // not error tracking - and render the toolbar anyway; missing+ // styles is a worse UX than nothing.styleLink.onerror = () => {toolbarLogger.error('config', 'Failed to load toolbar.css', { href: styleLink.href })- captureToolbarException(- new Error(`Failed to load toolbar.css from ${styleLink.href}`),- 'toolbar_css_load'- )toolbarPosthogJS.capture('toolbar css load failed', { href: styleLink.href })setDidLoadStyles(true)}diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.tsindex 20f0bf1d8efd..8c16b51d8292 100644--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts@@ -22,6 +22,7 @@ import { currentPageLogic } from '~/toolbar/stats/currentPageLogic'import { toolbarApi } from '~/toolbar/toolbarApi'import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'+import { ToolbarRequestError } from '~/toolbar/toolbarRequestError'import { CountedHTMLElement, ElementsEventType } from '~/toolbar/types'import {elementIsVisible,@@ -565,12 +566,9 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([}const { href, wildcardHref } = values- // We re-raise below to drive getElementStatsFailure; let the global- // loader handler report it once rather than capturing twice.const options = {context: 'load_heatmap_stats',reauthenticateOnForbidden: true,- captureOnError: false,}const result = url? // Paginating — the URL came from a previous response body.@@ -599,7 +597,13 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([return emptyElementsStatsPages}- if (!result.ok || !Array.isArray(result.data.results)) {+ // Tagged throw drives getElementStatsFailure without being reported+ // as an exception - a failed request is an expected outcome here.+ if (!result.ok) {+ throw new ToolbarRequestError('Error loading HeatMap data!', result.status)+ }+ // A 2xx body without a results array is a contract violation - a real bug.+ if (!Array.isArray(result.data.results)) {throw new Error('Error loading HeatMap data!')}diff --git a/frontend/src/toolbar/field-notes/fieldNotesLogic.ts b/frontend/src/toolbar/field-notes/fieldNotesLogic.tsindex 94d6e50850c5..23188d657642 100644--- a/frontend/src/toolbar/field-notes/fieldNotesLogic.ts+++ b/frontend/src/toolbar/field-notes/fieldNotesLogic.ts@@ -8,6 +8,7 @@ import { toolbarApi } from '~/toolbar/toolbarApi'import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'import { toolbarLogger } from '~/toolbar/toolbarLogger'import { captureToolbarException, toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'+import { isToolbarRequestError } from '~/toolbar/toolbarRequestError'import { ElementRect } from '~/toolbar/types'import { TOOLBAR_ID, elementToActionStep, getRectForElement, joinWithUiHost } from '~/toolbar/utils'import { captureAndUploadElementScreenshot } from '~/toolbar/utils/screenshot'@@ -244,7 +245,11 @@ export const fieldNotesLogic = kea<fieldNotesLogicType>([actions.setScreenshotUrl(joinWithUiHost(values.uiHost, `/uploaded_media/${mediaId}`))} catch (e: any) {toolbarLogger.warn('field-notes', 'Failed to capture screenshot')- captureToolbarException(e, 'field_note_screenshot')+ // A failed upload request (ToolbarRequestError) is expected; only a bug in+ // the screenshot capture itself is worth an exception.+ if (!isToolbarRequestError(e)) {+ captureToolbarException(e, 'field_note_screenshot')+ }}},deleteFieldNote: async ({ id }) => {diff --git a/frontend/src/toolbar/index.test.ts b/frontend/src/toolbar/index.test.tsindex 94ad571b3ef8..3162b93d09c8 100644--- a/frontend/src/toolbar/index.test.ts+++ b/frontend/src/toolbar/index.test.ts@@ -135,18 +135,24 @@ describe('Toolbar flag loading', () => {it.each([{name: 'transient network failure (fetch rejects)',- // `fetch` rejects only on network-level failures — these should be logged, not captured.setupMock: () => mockFetch.mockRejectedValueOnce(new TypeError('Failed to fetch')),- expectCapture: false,},{- name: 'unexpected error while applying flags (TypeError thrown in processing)',- // A null body makes `data.featureFlags` throw a TypeError during processing —- // a genuine bug that must still reach error tracking.+ name: 'unusable response body (null JSON)',setupMock: () => mockFetch.mockResolvedValueOnce({ json: async () => null }),- expectCapture: true,},- ])('reports only genuine errors as exceptions: $name', async ({ setupMock, expectCapture }) => {+ {+ name: 'non-JSON response body (proxy error page)',+ setupMock: () =>+ mockFetch.mockResolvedValueOnce({+ json: async () => {+ throw new SyntaxError('Unexpected token < in JSON')+ },+ }),+ },+ ])('never reports preload failures to error tracking: $name', async ({ setupMock }) => {+ // Every failure mode of the flags preload is request-shaped (network, proxy,+ // malformed body) - it must be logged, never captured as an exception.const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation()const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation()@@ -169,12 +175,8 @@ describe('Toolbar flag loading', () => {await (window as any).ph_load_toolbar(toolbarParams, mockPostHog)- if (expectCapture) {- expect(captureToolbarException).toHaveBeenCalledWith(expect.anything(), 'preloaded_flags_fetch')- } else {- expect(captureToolbarException).not.toHaveBeenCalled()- expect(consoleWarnSpy).toHaveBeenCalled()- }+ expect(captureToolbarException).not.toHaveBeenCalled()+ expect(consoleWarnSpy.mock.calls.length + consoleErrorSpy.mock.calls.length).toBeGreaterThan(0)consoleErrorSpy.mockRestore()consoleWarnSpy.mockRestore()diff --git a/frontend/src/toolbar/index.tsx b/frontend/src/toolbar/index.tsxindex f30af720f89f..9c50329ccbf3 100644--- a/frontend/src/toolbar/index.tsx+++ b/frontend/src/toolbar/index.tsx@@ -18,6 +18,8 @@ import { canonicalizeApiHost } from '~/toolbar/toolbarConfigLogic'import { posthogToolbarController, setToolbarRefs } from '~/toolbar/toolbarController'import { toolbarLogger } from '~/toolbar/toolbarLogger'import { captureToolbarException } from '~/toolbar/toolbarPosthogJS'+import { isToolbarRequestError } from '~/toolbar/toolbarRequestError'+import { safeFetch } from '~/toolbar/utils'import { ToolbarParams } from '~/types'interface InitKeaProps {@@ -49,10 +51,15 @@ const initKeaInToolbar = ({ routerHistory, routerLocation, beforePlugins }: Initreducer_key: reducerKey,action_key: actionKey,})- captureToolbarException(error, 'kea_loader', {- reducer_key: reducerKey,- action_key: actionKey,- })+ // Loaders throw ToolbarRequestError to drive their *Failure actions on+ // 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', {+ reducer_key: reducerKey,+ action_key: actionKey,+ })+ }},}),subscriptionsPlugin,@@ -103,15 +110,13 @@ export async function loadToolbar(toolbarParams: ToolbarParams, posthog?: PostHowindow.location.originconst flagsUrl = `${trimmedHost}/api/user/get_toolbar_preloaded_flags?key=${toolbarParams.toolbarFlagsKey}`- // Only the network call is wrapped here: `fetch` rejects solely on transient- // network-level failures (aborted request, ad blocker / browser extension,- // connectivity loss, CORS). The flags preload is best-effort and the toolbar- // degrades cleanly without it, so these are logged rather than surfaced as- // error-tracking exceptions. Parsing/applying the response is handled separately- // below so genuine bugs there still get captured.+ // The flags preload is best-effort and the toolbar degrades cleanly without it.+ // Every failure mode here is request-shaped (transient network failure, ad blocker,+ // CORS, a proxy returning a non-JSON error page, an invalid/stale flags key), so+ // nothing in this block is reported to error tracking - only logged.let response: Response | undefinedtry {- response = await fetch(flagsUrl, { credentials: 'include' })+ response = await safeFetch(flagsUrl, { credentials: 'include' })} catch (error) {toolbarLogger.warn('flags', 'Error fetching toolbar feature flags', {error: error instanceof Error ? error.message : String(error),@@ -125,14 +130,11 @@ export async function loadToolbar(toolbarParams: ToolbarParams, posthog?: PostHoposthog.featureFlags.overrideFeatureFlags({ flags: data.featureFlags })} else {toolbarLogger.error('flags', 'Feature flags not found', { response: data })- captureToolbarException(- new Error(`Toolbar feature flags not found: ${JSON.stringify(data)}`),- 'preloaded_flags'- )}} catch (error) {- toolbarLogger.error('flags', 'Error processing toolbar feature flags')- captureToolbarException(error, 'preloaded_flags_fetch')+ toolbarLogger.error('flags', 'Error processing toolbar feature flags', {+ error: error instanceof Error ? error.message : String(error),+ })}}}diff --git a/frontend/src/toolbar/product-tours/productToursLogic.ts b/frontend/src/toolbar/product-tours/productToursLogic.tsindex 625d6e66f029..4f420a43f064 100644--- a/frontend/src/toolbar/product-tours/productToursLogic.ts+++ b/frontend/src/toolbar/product-tours/productToursLogic.ts@@ -23,6 +23,7 @@ import { toolbarApi } from '~/toolbar/toolbarApi'import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'import { toolbarLogger } from '~/toolbar/toolbarLogger'import { captureToolbarException, toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'+import { ToolbarRequestError, isToolbarRequestError } from '~/toolbar/toolbarRequestError'import { ElementRect } from '~/toolbar/types'import { urls } from '~/toolbar/urls'import { TOOLBAR_ID, elementToActionStep, getRectForElement, joinWithUiHost } from '~/toolbar/utils'@@ -346,15 +347,15 @@ export const productToursLogic = kea<productToursLogicType>([if (!formValues.id) {return}- // Re-raise on failure so kea-forms runs submitTourFormFailure (resets the- // draft-save status). toolbarApi already logged it, so don't double-report.+ // Tagged throw so kea-forms runs submitTourFormFailure (resets the+ // draft-save status) without reporting the failed request as an exception.const result = await toolbarApi.productTours.updateDraft(formValues.id,await buildDraftPayload(formValues, values.tours),- { context: 'save_product_tour_draft', captureOnError: false }+ { context: 'save_product_tour_draft' })if (!result.ok) {- throw new Error('Failed to save draft')+ throw new ToolbarRequestError('Failed to save draft', result.status)}},},@@ -475,7 +476,11 @@ export const productToursLogic = kea<productToursLogicType>([const inferenceData = inferSelector(element)?.selectorconst screenshot = await captureAndUploadElementScreenshot(element).catch((e) => {toolbarLogger.warn('product_tours', 'Failed to capture element screenshot')- captureToolbarException(e, 'product_tour_screenshot')+ // A failed upload request (ToolbarRequestError) is expected; only a bug in+ // the screenshot capture itself is worth an exception.+ if (!isToolbarRequestError(e)) {+ captureToolbarException(e, 'product_tour_screenshot')+ }return null})diff --git a/frontend/src/toolbar/screenshot-upload/screenshotUploadLogic.ts b/frontend/src/toolbar/screenshot-upload/screenshotUploadLogic.tsindex 8f24880f3241..874fdae70565 100644--- a/frontend/src/toolbar/screenshot-upload/screenshotUploadLogic.ts+++ b/frontend/src/toolbar/screenshot-upload/screenshotUploadLogic.ts@@ -5,6 +5,8 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'import { toolbarApi } from '~/toolbar/toolbarApi'import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'+import { ToolbarRequestError } from '~/toolbar/toolbarRequestError'+import { safeFetch } from '~/toolbar/utils'import { captureElementScreenshot, uploadScreenshot } from '~/toolbar/utils/screenshot'import { EventDefinition } from '~/types'@@ -89,22 +91,28 @@ export const screenshotUploadLogic = kea<screenshotUploadLogicType>([return null}- const blob = await fetch(previewUrl).then((r) => r.blob())+ // safeFetch can hand back a synthetic 502 JSON response (customer fetch+ // wrapper) - never upload that body as the screenshot.+ const previewResponse = await safeFetch(previewUrl)+ if (!previewResponse.ok) {+ throw new ToolbarRequestError('Failed to read screenshot preview', previewResponse.status)+ }+ const blob = await previewResponse.blob()const { mediaId } = await uploadScreenshot(blob)breakpoint()- // Re-raise on failure so submitUploadFailure surfaces the toast; toolbarApi- // already logged it, so don't double-report via the global loader handler.+ // Tagged throw drives submitUploadFailure (which surfaces the toast)+ // without reporting the failed request as an exception.const result = await toolbarApi.objectMediaPreviews.create({uploaded_media_id: mediaId,event_definition_id: selectedDefinition.id,},- { context: 'create_object_media_preview', captureOnError: false }+ { context: 'create_object_media_preview' })breakpoint()if (!result.ok) {- throw new Error(result.error.detail)+ throw new ToolbarRequestError(result.error.detail, result.status)}return { success: true }diff --git a/frontend/src/toolbar/toolbarApi.ts b/frontend/src/toolbar/toolbarApi.tsindex 469e589a1cb0..ef440c9f85b9 100644--- a/frontend/src/toolbar/toolbarApi.ts+++ b/frontend/src/toolbar/toolbarApi.ts@@ -6,7 +6,6 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'import { toolbarFetch } from '~/toolbar/toolbarFetch'import { toolbarLogger } from '~/toolbar/toolbarLogger'-import { captureToolbarException } from '~/toolbar/toolbarPosthogJS'import type { ElementsEventType, WebExperiment } from '~/toolbar/types'import type { ActionType, CombinedFeatureFlagAndValueType, EventDefinition, ProductTour, Survey } from '~/types'@@ -24,16 +23,20 @@ import type { ActionType, CombinedFeatureFlagAndValueType, EventDefinition, Prod* so no caller needs a `try/catch` and no listener can leak an unhandled rejection.* - It always parses the body and returns a discriminated-union `ToolbarApiResult`,* so every call site branches on `result.ok` the same way.- * - It centralizes observability: every failure is logged via `toolbarLogger`, and- * genuinely-unexpected failures (network errors, 5xx, malformed JSON) are reported- * to error tracking. Auth (401/403) and client (4xx) errors are expected outcomes —- * they are logged but not reported as exceptions.+ * - It NEVER reports request failures to error tracking. Failed requests - auth+ * (401/403), client (4xx), server (5xx), network, malformed bodies - are expected+ * outcomes of running on customer pages; they are logged via `toolbarLogger` and+ * visible in the `toolbar api request` telemetry, but they are not exceptions.+ * Error tracking is reserved for genuine toolbar bugs.* - Per-request telemetry (`toolbar api request`) is emitted by `toolbarFetch` itself.** What stays at the call site is only what is genuinely call-site specific: the* fallback value to use on failure, and any feature side effects (e.g. resetting a* form, disabling a mode). Toasting and re-authentication are opt-in via options so- * that loaders stay quiet while user-initiated writes can surface a message.+ * that loaders stay quiet while user-initiated writes can surface a message. A call+ * site that needs its kea `*Failure` action to fire converts a failed result into a+ * `throw new ToolbarRequestError(...)` - the global loader handler logs those without+ * capturing them.** Auth flows (OAuth code exchange, token refresh, the reachability HEAD check) and the* pre-mount feature-flag preload deliberately do NOT use this — they run before the@@ -79,13 +82,6 @@ export interface ToolbarApiOptions {* additionally kicks off re-authentication. Defaults to `false`.*/reauthenticateOnForbidden?: boolean- /**- * Report unexpected failures (network / 5xx / malformed JSON) to error tracking.- * Defaults to `true`. Set to `false` when the caller deliberately re-raises the- * failure (e.g. a kea loader that throws to drive its own `*Failure` reducer) so the- * exception is only captured once.- */- captureOnError?: boolean/*** Passed through to `toolbarFetch`. Use `'use-as-provided'` for pagination URLs that* come from a response body (they are pinned to the uiHost/apiHost origin). Defaults@@ -143,19 +139,13 @@ async function request<T>(payload: Record<string, any> | FormData | undefined,options: ToolbarApiOptions): Promise<ToolbarApiResult<T>> {- const {- context,- toastOnError = false,- reauthenticateOnForbidden = false,- captureOnError = true,- urlConstruction = 'full',- } = options+ const { context, toastOnError = false, reauthenticateOnForbidden = false, urlConstruction = 'full' } = optionsconst pathname = pathnameForLog(url)let response: Responsetry {response = await toolbarFetch(url, method, payload, urlConstruction)- } catch (e) {+ } catch {const error: ToolbarApiErrorInfo = {status: 0,detail: 'Network error',@@ -164,9 +154,6 @@ async function request<T>(isNetworkError: true,}toolbarLogger.error('api', `Request failed (network): ${context}`, { context, method, pathname })- if (captureOnError) {- captureToolbarException(e, context, { reason: 'network' })- }emitToast(toastOnError, error)return { ok: false, status: 0, data: null, error }}@@ -181,7 +168,7 @@ async function request<T>(try {const data = (await response.json()) as Treturn { ok: true, status, data }- } catch (e) {+ } catch {const error: ToolbarApiErrorInfo = {status,detail: 'The server returned a malformed response.',@@ -190,9 +177,6 @@ async function request<T>(isNetworkError: false,}toolbarLogger.error('api', `Response was not valid JSON: ${context}`, { context, method, pathname, status })- if (captureOnError) {- captureToolbarException(e, context, { reason: 'invalid_json', status })- }emitToast(toastOnError, error)return { ok: false, status, data: null, error }}@@ -213,13 +197,10 @@ async function request<T>(toolbarConfigLogic.actions.authenticate()}- // Server errors are unexpected and worth an exception; auth and other client errors- // are expected outcomes (stale session, validation) — log them but don't report.+ // Any HTTP failure is an expected outcome of talking to the API (stale session,+ // validation, backend incident) - log it, never report it to error tracking.if (isServerError) {toolbarLogger.error('api', `Request failed (server): ${context}`, { context, method, pathname, status })- if (captureOnError) {- captureToolbarException(new Error(`${context}: HTTP ${status}`), context, { status })- }} else {toolbarLogger.warn('api', `Request failed: ${context}`, { context, method, pathname, status })}diff --git a/frontend/src/toolbar/toolbarAuth.ts b/frontend/src/toolbar/toolbarAuth.tsindex 3b9207ef1b42..45c8cf4a00e7 100644--- a/frontend/src/toolbar/toolbarAuth.ts+++ b/frontend/src/toolbar/toolbarAuth.ts@@ -2,6 +2,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { toolbarLogger } from '~/toolbar/toolbarLogger'import { captureToolbarException, toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'+import { ToolbarRequestError, isToolbarRequestError } from '~/toolbar/toolbarRequestError'import { asNonEmptyString, safeFetch } from '~/toolbar/utils'import { toolbarConfigLogic } from './toolbarConfigLogic'@@ -22,24 +23,44 @@ export async function refreshOAuthTokens(refreshPromise = (async () => {const startTime = performance.now()try {- const response = await safeFetch(`${uiHost}/api/user/toolbar_oauth_refresh/`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ refresh_token: currentRefreshToken, client_id: clientId }),- })+ // Every failure below is an expected request outcome (expired/revoked refresh+ // token, network hiccup, proxy error page) - tracked via the capture event and+ // logs, never reported to error tracking.+ let response: Response+ try {+ response = await safeFetch(`${uiHost}/api/user/toolbar_oauth_refresh/`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ refresh_token: currentRefreshToken, client_id: clientId }),+ })+ } catch {+ toolbarPosthogJS.capture('toolbar token refresh', {+ status: 'network_error',+ duration_ms: Math.round(performance.now() - startTime),+ })+ throw new ToolbarRequestError('Refresh failed: network error')+ }if (!response.ok) {- const err = new Error(`Refresh failed: ${response.status}`)toolbarPosthogJS.capture('toolbar token refresh', {status: 'error',http_status: response.status,duration_ms: Math.round(performance.now() - startTime),})- captureToolbarException(err, 'token_refresh')- throw err+ throw new ToolbarRequestError(`Refresh failed: ${response.status}`, response.status)}- const data = await response.json()+ let data: OAuthTokens+ try {+ data = await response.json()+ } catch {+ toolbarPosthogJS.capture('toolbar token refresh', {+ status: 'invalid_response',+ http_status: response.status,+ duration_ms: Math.round(performance.now() - startTime),+ })+ throw new ToolbarRequestError('Refresh failed: malformed response', response.status)+ }toolbarPosthogJS.capture('toolbar token refresh', {status: 'success',duration_ms: Math.round(performance.now() - startTime),@@ -90,10 +111,22 @@ export async function withTokenRefresh(return response}toolbarConfigLogic.actions.setOAuthTokens(access, refresh, clientId)- return await retryRequest(access)+ try {+ return await retryRequest(access)+ } catch {+ // The refresh succeeded but the replayed request failed at the network level -+ // an expected request outcome. Hand back the original 401 so callers treat it+ // as an ordinary failed response instead of an exception.+ toolbarLogger.warn('auth', 'Request replay after token refresh failed at network level')+ return response+ }} catch (e) {toolbarLogger.error('auth', 'Token refresh retry failed', { status: response.status })- captureToolbarException(e, 'token_refresh_retry')+ // Failed refreshes are expected request outcomes (ToolbarRequestError) - only a+ // genuine bug in the refresh/retry code itself is worth an exception.+ if (!isToolbarRequestError(e)) {+ captureToolbarException(e, 'token_refresh_retry')+ }lemonToast.error('Please re-authenticate to continue using the toolbar.')toolbarConfigLogic.actions.tokenExpired()return responsediff --git a/frontend/src/toolbar/toolbarConfigLogic.ts b/frontend/src/toolbar/toolbarConfigLogic.tsindex ce34be65ac71..fef4f25fd979 100644--- a/frontend/src/toolbar/toolbarConfigLogic.ts+++ b/frontend/src/toolbar/toolbarConfigLogic.ts@@ -15,6 +15,7 @@ import {OAUTH_LOCALSTORAGE_KEY,PKCE_STORAGE_KEY,readToolbarAuthHash,+ safeFetch,} from './utils'export type ApiHostSource = 'posthog_api_host' | 'api_url' | 'fallback_rejected' | 'fallback_absent'@@ -635,7 +636,7 @@ function verifyUiHostReachability(}const checkStart = Date.now()- void fetch(`${values.uiHost}/toolbar_oauth/check`, {+ void safeFetch(`${values.uiHost}/toolbar_oauth/check`, {method: 'HEAD',mode: 'cors',signal: AbortSignal.timeout(5000),@@ -657,13 +658,17 @@ function verifyUiHostReachability(}).catch((error: unknown) => {actions.setAuthStatus('error')- captureToolbarException(error, 'ui_host_check', {- error_type: classifyFetchError(error),- })+ const errorType = classifyFetchError(error)+ // Timeouts, network/CORS failures, and HTTP errors are expected on customer+ // pages (offline, ad blockers, CSP, misconfigured uiHost) - the capture event+ // below tracks them. Only an unclassifiable error hints at a toolbar bug.+ if (errorType === 'unknown') {+ captureToolbarException(error, 'ui_host_check', { error_type: errorType })+ }toolbarPosthogJS.capture('toolbar ui host check', {...checkBaseProps,status: 'error',- error_type: classifyFetchError(error),+ error_type: errorType,duration_ms: Date.now() - checkStart,})@@ -738,14 +743,17 @@ async function exchangeCodeForTokens(code_verifier: pkceData.verifier,})+ // Every failure in the exchange is an expected request outcome (stale/reused code,+ // expired PKCE, network hiccup, proxy error page) - tracked via the capture events+ // and logs, never reported to error tracking.const startTime = performance.now()try {- const res = await fetch(tokenEndpoint, {+ const res = await safeFetch(tokenEndpoint, {method: 'POST',headers: { 'Content-Type': 'application/x-www-form-urlencoded' },body: body.toString(),})- const data = await res.json()+ const data = await res.json().catch(() => null)const access = asNonEmptyString(data?.access_token)const refresh = asNonEmptyString(data?.refresh_token)if (access && refresh) {@@ -760,19 +768,18 @@ async function exchangeCodeForTokens(toolbarPosthogJS.capture('toolbar oauth exchange', {status: 'error',error: errorString,+ http_status: res.status,duration_ms: Math.round(performance.now() - startTime),})- toolbarLogger.error('auth', 'Token exchange failed', { error: errorString })- captureToolbarException(new Error(`Token exchange failed: ${errorString}`), 'token_exchange')+ toolbarLogger.error('auth', 'Token exchange failed', { error: errorString, status: res.status })lemonToast.error('Authentication failed. Please try again.')return false- } catch (err) {+ } catch {toolbarPosthogJS.capture('toolbar oauth exchange', {status: 'network_error',duration_ms: Math.round(performance.now() - startTime),})toolbarLogger.error('auth', 'Token exchange network error')- captureToolbarException(err, 'token_exchange_network')lemonToast.error('Authentication failed due to a network error. Please try again.')return false} finally {diff --git a/frontend/src/toolbar/toolbarFetch.ts b/frontend/src/toolbar/toolbarFetch.tsindex 94d9a5f4c3ef..8e16fafba999 100644--- a/frontend/src/toolbar/toolbarFetch.ts+++ b/frontend/src/toolbar/toolbarFetch.ts@@ -5,6 +5,7 @@ import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'import { withTokenRefresh } from './toolbarAuth'import { toolbarConfigLogic } from './toolbarConfigLogic'+import { ToolbarRequestError } from './toolbarRequestError'import { safeFetch } from './utils'/**@@ -147,7 +148,7 @@ export async function toolbarUploadMedia(file: File): Promise<{ id: string; url:// toolbarFetch (which would return a stub 401 and trip tokenExpired// telemetry / toasts for a user who was never authenticated).if (!toolbarConfigLogic.findMounted()?.values.accessToken) {- throw new Error('Toolbar not authenticated')+ throw new ToolbarRequestError('Toolbar not authenticated', 401)}// Route through toolbarFetch so authenticated uploads share the single@@ -161,13 +162,13 @@ export async function toolbarUploadMedia(file: File): Promise<{ id: string; url:if (response.status === 401) {// Session was valid at start but expired and refresh failed.toolbarConfigLogic.findMounted()?.actions.tokenExpired()- throw new Error('Authentication expired')+ throw new ToolbarRequestError('Authentication expired', 401)}if (!response.ok) {const errorData = await response.json().catch(() => ({}))// toolbarFetch already calls tokenExpired() on 403, so no need to repeat it here.- throw new Error(errorData.detail || `Upload failed: ${response.status}`)+ throw new ToolbarRequestError(errorData.detail || `Upload failed: ${response.status}`, response.status)}const data: ToolbarMediaUploadResponse = await response.json()diff --git a/frontend/src/toolbar/toolbarLogger.ts b/frontend/src/toolbar/toolbarLogger.tsindex 6fadb3d63b20..43752e353721 100644--- a/frontend/src/toolbar/toolbarLogger.ts+++ b/frontend/src/toolbar/toolbarLogger.ts@@ -119,12 +119,15 @@ function sendLog(level: LogLevel, context: string, message: string, properties?:if (navigator.sendBeacon) {navigator.sendBeacon(url, new Blob([JSON.stringify(body)], { type: 'application/json' }))} else {- void fetch(url, {+ // Swallow rejections: an unhandled rejection here would surface on the+ // customer's page (and in error tracking) just because a log didn't send.+ // nosemgrep: toolbar-no-raw-fetch - can't use safeFetch (utils.ts imports this logger)+ fetch(url, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(body),keepalive: true,- })+ }).catch(() => {})}} catch {// Never throw on customer pages — matches the contract of toolbarPosthogJS.capture()diff --git a/frontend/src/toolbar/toolbarRequestError.ts b/frontend/src/toolbar/toolbarRequestError.tsnew file mode 100644index 000000000000..34f9c394c319--- /dev/null+++ b/frontend/src/toolbar/toolbarRequestError.ts@@ -0,0 +1,34 @@+/**+ * An expected request failure: the backend said no (4xx/5xx), the network was unavailable,+ * or the response body was unusable. These are normal outcomes of talking to the API from+ * a customer's page - they must never be reported to error tracking.+ *+ * `toolbarApi` itself never throws (it returns a `ToolbarApiResult` union). Logics that+ * need a kea `*Failure` action to fire (to drive UI state or a toast) convert a failed+ * result into a throw - that throw must be a `ToolbarRequestError`, so the global kea+ * loader handler (see `index.tsx`) can log it without capturing an exception. Throwing a+ * plain `Error` from a loader is reserved for genuine bugs, which SHOULD be captured.+ */+export class ToolbarRequestError extends Error {+ /** HTTP status of the failed response, or 0 for a network-level failure. */+ status: number++ constructor(message: string, status: number = 0) {+ super(message)+ this.name = 'ToolbarRequestError'+ this.status = status+ }+}++/**+ * Preferred over a bare `instanceof` check: on customer pages the error can cross+ * realm/bundle boundaries (duplicate toolbar bundles, page wrappers around fetch/DOM+ * APIs), where class identity is lost. Fall back to the `name` tag so a tagged request+ * failure is never misclassified as a genuine bug.+ */+export function isToolbarRequestError(error: unknown): boolean {+ if (error instanceof ToolbarRequestError) {+ return true+ }+ return typeof error === 'object' && error !== null && (error as { name?: unknown }).name === 'ToolbarRequestError'+}diff --git a/frontend/src/toolbar/utils.ts b/frontend/src/toolbar/utils.tsindex 72afde7c5197..fed7a62633e6 100644--- a/frontend/src/toolbar/utils.ts+++ b/frontend/src/toolbar/utils.ts@@ -24,6 +24,7 @@ export const asNonEmptyString = (v: unknown): string | null => (typeof v === 'st// any non-object value into a synthetic failed response so the toolbar's OAuth chain and its// callers can treat it as an ordinary request failure rather than crashing.export async function safeFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {+ // nosemgrep: toolbar-no-raw-fetch - this IS the wrapper the rule points everyone toconst response = await fetch(input, init)if (response && typeof response === 'object') {return response