: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(error-tracking): skip autocaptured dead-scope rejections (#119162)
posthog[bot]7aeb4a8cdf48
diff --git a/frontend/src/lib/api-error.ts b/frontend/src/lib/api-error.tsindex 72e471bbf726..9ca0f2b3f0b3 100644--- a/frontend/src/lib/api-error.ts+++ b/frontend/src/lib/api-error.ts@@ -93,8 +93,16 @@ export function isScopeNotFoundError(error: unknown): boolean {if (failure?.status !== 404) {return false}- const detail = failure.detail ?? failure.data?.detail- return typeof detail === 'string' && SCOPE_NOT_FOUND_DETAILS.has(detail)+ return isScopeNotFoundMessage(failure.detail ?? failure.data?.detail)+}++/**+ * Whether a message is the `detail` of a dead scope. An `ApiError` takes its message from that+ * `detail`, and the automatic unhandled-rejection capture keeps the message but not the status, so+ * `before_send` can only match on this.+ */+export function isScopeNotFoundMessage(message: unknown): boolean {+ return typeof message === 'string' && SCOPE_NOT_FOUND_DETAILS.has(message)}/** DRF code of a security access rule refusal (products/security). Keep in sync with the backend. */diff --git a/frontend/src/lib/utils/exceptionFilters.test.ts b/frontend/src/lib/utils/exceptionFilters.test.tsnew file mode 100644index 000000000000..0f5f569f0a65--- /dev/null+++ b/frontend/src/lib/utils/exceptionFilters.test.ts@@ -0,0 +1,146 @@+import { CaptureResult } from 'posthog-js'++import { NETWORK_ERROR_MESSAGES } from 'lib/api-error'++import {+ dropHandledAuthGateExceptions,+ dropInjectedScriptReferenceErrors,+ dropScopeNotFoundExceptions,+ dropUnactionableNetworkExceptions,+} from './exceptionFilters'++const exceptionEvent = (exceptions: Record<string, unknown>[], event = '$exception'): CaptureResult => ({+ uuid: 'example-uuid',+ event,+ properties: { $exception_list: exceptions },+})++const unhandledReferenceError = (value: string, extra: Record<string, unknown> = {}): Record<string, unknown> => ({+ type: 'ReferenceError',+ value,+ mechanism: { type: 'generic', handled: false },+ ...extra,+})++describe('exceptionFilters', () => {+ it.each([+ ['dropScopeNotFoundExceptions', dropScopeNotFoundExceptions],+ ['dropHandledAuthGateExceptions', dropHandledAuthGateExceptions],+ ['dropUnactionableNetworkExceptions', dropUnactionableNetworkExceptions],+ ['dropInjectedScriptReferenceErrors', dropInjectedScriptReferenceErrors],+ ])('%s passes through non-exception events and exceptions with no list', (_, filter) => {+ const pageview = exceptionEvent([{ type: 'Error', value: 'Project not found.' }], '$pageview')+ const bare: CaptureResult = { uuid: 'example-uuid', event: '$exception', properties: {} }++ expect(filter(pageview)).toBe(pageview)+ expect(filter(bare)).toBe(bare)+ })++ describe('dropScopeNotFoundExceptions', () => {+ it.each([+ ['an uncaught dead-project rejection', ['Project not found.'], false],+ ['an uncaught dead-organization rejection', ['Organization not found.'], false],+ ['a dead-scope rejection wrapped as a cause', ['Failed to load', 'Project not found.'], false],+ ['an unrelated exception', ['Not found.'], true],+ ])('handles %s', (_, values, kept) => {+ const event = exceptionEvent(values.map((value) => ({ type: 'Error', value })))++ expect(dropScopeNotFoundExceptions(event)).toBe(kept ? event : null)+ })+ })++ describe('dropHandledAuthGateExceptions', () => {+ // Each value is the message `ApiError` sets from the backend `detail` for a handled auth gate.+ it.each([+ ['2FA setup required', [{ type: 'Error', value: '2FA setup required' }], false],+ ['2FA verification required', [{ type: 'Error', value: '2FA verification required' }], false],+ [+ 'a re-auth prompt',+ [{ type: 'Error', value: 'This action requires you to be recently authenticated.' }],+ false,+ ],+ [+ 'a gate wrapped as a cause',+ [+ { type: 'Error', value: 'reverseProxyCheckerLogic: query failed' },+ { type: 'Error', value: '2FA setup required' },+ ],+ false,+ ],+ ['a real crash', [{ type: 'TypeError', value: 'x is not a function' }], true],+ ])('handles %s', (_, exceptions, kept) => {+ const event = exceptionEvent(exceptions)++ expect(dropHandledAuthGateExceptions(event)).toBe(kept ? event : null)+ })+ })++ describe('dropUnactionableNetworkExceptions', () => {+ // The asymmetry is the point of the filter: offline and navigating describe the client's+ // situation, while `network` means a request failed while the user was online and staying put.+ it.each([+ ['a request while offline', [{ type: 'NetworkError', value: NETWORK_ERROR_MESSAGES.offline }], false],+ [+ 'a request while the page was closing',+ [{ type: 'NetworkError', value: NETWORK_ERROR_MESSAGES.navigating }],+ false,+ ],+ [+ 'a failure wrapped as a cause',+ [+ { type: 'Error', value: 'loadSavedHeatmaps failed' },+ { type: 'NetworkError', value: NETWORK_ERROR_MESSAGES.navigating },+ ],+ false,+ ],+ [+ 'an unexplained connection failure',+ [{ type: 'NetworkError', value: NETWORK_ERROR_MESSAGES.network }],+ true,+ ],+ [+ 'an unrelated error that carries a network message',+ [{ type: 'Error', value: NETWORK_ERROR_MESSAGES.offline }],+ true,+ ],+ ])('handles %s', (_, exceptions, kept) => {+ const event = exceptionEvent(exceptions)++ expect(dropUnactionableNetworkExceptions(event)).toBe(kept ? event : null)+ })+ })++ describe('dropInjectedScriptReferenceErrors', () => {+ it.each([+ [+ "the WebKit wording, Can't find variable: WeixinJSBridge",+ [unhandledReferenceError("Can't find variable: WeixinJSBridge")],+ false,+ ],+ ['the V8 wording, zaloJSV2 is not defined', [unhandledReferenceError('zaloJSV2 is not defined')], false],+ [+ 'a ReferenceError from our own bundle, which carries a stack',+ [+ unhandledReferenceError('foo is not defined', {+ stacktrace: { frames: [{ source: 'https://example.com/static/chunk.js' }] },+ }),+ ],+ true,+ ],+ [+ 'a handled ReferenceError',+ [{ type: 'ReferenceError', value: 'foo is not defined', mechanism: { handled: true } }],+ true,+ ],+ [+ 'a non-ReferenceError with the same message shape',+ [{ type: 'TypeError', value: 'foo is not defined', mechanism: { handled: false } }],+ true,+ ],+ ])('handles %s', (_, exceptions, kept) => {+ const event = exceptionEvent(exceptions)++ expect(dropInjectedScriptReferenceErrors(event)).toBe(kept ? event : null)+ })+ })+})diff --git a/frontend/src/lib/utils/exceptionFilters.ts b/frontend/src/lib/utils/exceptionFilters.tsnew file mode 100644index 000000000000..564b64a8a4be--- /dev/null+++ b/frontend/src/lib/utils/exceptionFilters.ts@@ -0,0 +1,100 @@+import { BeforeSendFn } from 'posthog-js'++import { UNACTIONABLE_NETWORK_ERROR_MESSAGES, isScopeNotFoundMessage } from 'lib/api-error'++/** One entry of the `$exception_list` that posthog-js builds, reduced to the fields these filters read. */+interface CapturedException {+ type?: string+ value?: string+ mechanism?: { handled?: boolean }+ stacktrace?: { frames?: unknown[] }+}++/**+ * Builds a `before_send` filter that drops an `$exception` event when `isNoise` matches its exception+ * list. posthog-js appends each wrapped `cause` to that list, so a filter that reads only the first+ * entry misses an expected error that a caller rethrew inside another one.+ */+function dropExceptionsWhen(isNoise: (exceptions: CapturedException[]) => boolean): BeforeSendFn {+ return (event) => {+ if (event?.event !== '$exception') {+ return event+ }+ const exceptions: CapturedException[] = event.properties?.$exception_list ?? []+ return isNoise(exceptions) ? null : event+ }+}++/**+ * Drops an uncaught rejection from a request on a deleted or inaccessible project or organization.+ * The kea loaders and `shouldReportApiFailure` already excuse this failure, but a promise that no+ * caller handles reaches error tracking through autocapture and skips those checks.+ */+export const dropScopeNotFoundExceptions = dropExceptionsWhen((exceptions) =>+ exceptions.some((exception) => isScopeNotFoundMessage(exception?.value))+)++/**+ * The `detail` messages the backend sends with the three handled auth-gate 403s. Keep in sync with:+ *+ * two_factor_setup_required - posthog/helpers/two_factor_session.py+ * two_factor_verification_required - posthog/helpers/two_factor_session.py+ * sensitive_action_required_reauth - posthog/permissions.py (TimeSensitiveActionPermission)+ */+const HANDLED_AUTH_GATE_MESSAGES: ReadonlySet<string> = new Set([+ '2FA setup required',+ '2FA verification required',+ 'This action requires you to be recently authenticated.',+])++/**+ * Drops a handled auth gate. `apiStatusLogic` turns these 403s into the 2FA setup or verify flow or a+ * re-auth prompt, so a rejected request is expected control flow, not a crash. `$exception_list`+ * keeps only the error type, message and stack, and the DRF `code` never reaches `before_send`, so+ * the match is on the message, which `ApiError` sets from the response `detail`.+ */+export const dropHandledAuthGateExceptions = dropExceptionsWhen((exceptions) =>+ exceptions.some((exception) => exception?.value != null && HANDLED_AUTH_GATE_MESSAGES.has(exception.value))+)++/**+ * Drops a request the browser never sent because the client was offline or the document was being+ * torn down. Neither is a defect, and both arrive as unhandled rejections from whichever logic was+ * fetching, so each one fingerprints against a different stack and files its own issue. A+ * `NetworkError` with reason `network` is kept on purpose: a request that failed while the user was+ * online and staying put is worth seeing.+ */+export const dropUnactionableNetworkExceptions = dropExceptionsWhen((exceptions) =>+ exceptions.some(+ (exception) =>+ exception?.type === 'NetworkError' &&+ exception.value != null &&+ UNACTIONABLE_NETWORK_ERROR_MESSAGES.has(exception.value)+ )+)++/**+ * Browser engines word an unknown-identifier ReferenceError in one of two ways: WebKit says "Can't+ * find variable: X", V8 and SpiderMonkey say "X is not defined". Both name a single identifier. Our+ * own bundle never leaves such an identifier undefined at runtime.+ */+const UNKNOWN_IDENTIFIER_REFERENCE_ERROR = /^(Can't find variable: \S+|\S+ is not defined)$/++/**+ * Drops a ReferenceError that a browser extension or an in-app browser injected into the page, for an+ * identifier our code never defines. posthog-js captures it through the global handler with no stack+ * frames, because the throwing script is not ours. A real ReferenceError in our own bundle carries a+ * stack, so the empty-stack check keeps those. Each injected variant fingerprints to its own issue,+ * so the whole class is dropped here.+ */+export const dropInjectedScriptReferenceErrors = dropExceptionsWhen(+ (exceptions) =>+ !exceptions.some((exception) => (exception?.stacktrace?.frames?.length ?? 0) > 0) &&+ exceptions.every((exception) => exception?.mechanism?.handled === false) &&+ exceptions.some(+ (exception) =>+ exception?.type === 'ReferenceError' &&+ exception.value != null &&+ UNKNOWN_IDENTIFIER_REFERENCE_ERROR.test(exception.value)+ )+)diff --git a/frontend/src/loadPostHogJS.tsx b/frontend/src/loadPostHogJS.tsxindex 380c3681495e..c66942412b78 100644--- a/frontend/src/loadPostHogJS.tsx+++ b/frontend/src/loadPostHogJS.tsx@@ -4,6 +4,12 @@ import { FEATURE_FLAGS } from 'lib/constants'import { isOAuthMode } from 'lib/oauth/oauthClient'import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'import { isEmbeddedPageFrame } from 'lib/utils/embeddedPageFrame'+import {+ dropHandledAuthGateExceptions,+ dropInjectedScriptReferenceErrors,+ dropScopeNotFoundExceptions,+ dropUnactionableNetworkExceptions,+} from 'lib/utils/exceptionFilters'import { getAppContext, isHobbyDeployment } from 'lib/utils/getAppContext'import { redactMetricVariableUrls } from 'lib/utils/metricVariableUrlRedaction'import { identifyInstanceInPostHog, identifyUserInPostHog } from 'lib/utils/posthogIdentity'@@ -117,11 +123,16 @@ export function loadPostHogJS(): void {__capturePostHogExceptions: true,},metrics: { network: true, serviceName: 'posthog-app' },- // A page in a frame counts its own pageviews, so its events say so and analysis can filter them.- // `register` would persist the property in storage the main window shares, so it is stamped per event.- before_send: isEmbeddedPageFrame()- ? [redactMetricVariableUrls, stampEmbeddedPageFrame]- : redactMetricVariableUrls,+ before_send: [+ dropScopeNotFoundExceptions,+ dropHandledAuthGateExceptions,+ dropUnactionableNetworkExceptions,+ dropInjectedScriptReferenceErrors,+ redactMetricVariableUrls,+ // A page in a frame counts its own pageviews, so its events say so and analysis can filter them.+ // `register` would persist the property in storage the main window shares, so it is stamped per event.+ ...(isEmbeddedPageFrame() ? [stampEmbeddedPageFrame] : []),+ ],loaded: (loadedInstance) => {if (loadedInstance.sessionRecording) {loadedInstance.sessionRecording._forceAllowLocalhostNetworkCapture = true