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(api): classify fetch failures that never reach the server (#81711)

Carlos Marchal920b0b39ce6b
diff --git a/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.test.ts b/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.test.ts
index 53eba3cdf081..cacc91fb547b 100644
--- a/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.test.ts
+++ b/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.test.ts
@@ -1,4 +1,10 @@
-import { dropHandledAuthGateExceptions, dropReadOnlyExceptions } from './selfReadOnlyModeLogic'
+import { NETWORK_ERROR_MESSAGES } from 'lib/api-error'
+
+import {
+ dropHandledAuthGateExceptions,
+ dropReadOnlyExceptions,
+ dropUnactionableNetworkExceptions,
+} from './selfReadOnlyModeLogic'
describe('dropReadOnlyExceptions', () => {
it('passes non-exception events through unchanged', () => {
@@ -93,3 +99,46 @@ describe('dropHandledAuthGateExceptions', () => {
expect(dropHandledAuthGateExceptions(null)).toBeNull()
})
})
+
+describe('dropUnactionableNetworkExceptions', () => {
+ const exceptionWith = (value: string, type = 'NetworkError'): { event: string; properties: any } => ({
+ event: '$exception',
+ properties: { $exception_list: [{ type, value }] },
+ })
+
+ // The asymmetry is the whole point of the filter: the first two say something about the client's
+ // situation, the third says a request failed while the user was online and staying put.
+ it.each([
+ ['device is offline', NETWORK_ERROR_MESSAGES.offline, true],
+ ['page was closing', NETWORK_ERROR_MESSAGES.navigating, true],
+ ['an unexplained connection failure', NETWORK_ERROR_MESSAGES.network, false],
+ ])('given %s, drops the event: %s', (_desc, value, dropped) => {
+ const event = exceptionWith(value)
+ expect(dropUnactionableNetworkExceptions(event)).toBe(dropped ? null : event)
+ })
+
+ it('keeps an unrelated error that happens to carry a network message', () => {
+ // Matching on the message alone would let any `Error` with this text be silenced
+ const event = exceptionWith(NETWORK_ERROR_MESSAGES.offline, 'Error')
+ expect(dropUnactionableNetworkExceptions(event)).toBe(event)
+ })
+
+ it('drops the failure even when it sits deeper in the exception list', () => {
+ // posthog-js appends the wrapped cause, so `NetworkError` is not always first
+ const event = {
+ event: '$exception',
+ properties: {
+ $exception_list: [
+ { type: 'Error', value: 'loadSavedHeatmaps failed' },
+ { type: 'NetworkError', value: NETWORK_ERROR_MESSAGES.navigating },
+ ],
+ },
+ }
+ expect(dropUnactionableNetworkExceptions(event)).toBeNull()
+ })
+
+ it('tolerates missing properties and a missing exception list', () => {
+ expect(dropUnactionableNetworkExceptions({ event: '$exception' })).toEqual({ event: '$exception' })
+ expect(dropUnactionableNetworkExceptions(null)).toBeNull()
+ })
+})
diff --git a/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.ts b/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.ts
index 85d79eb86e56..c7c7f70f0d53 100644
--- a/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.ts
+++ b/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.ts
@@ -14,6 +14,7 @@ import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
+import { UNACTIONABLE_NETWORK_ERROR_MESSAGES } from 'lib/api-error'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { setReadOnlyGetter, setReadOnlyNotifier } from 'lib/readOnlyGuard'
@@ -77,6 +78,30 @@ export function dropHandledAuthGateExceptions<T extends { event?: string; proper
return event
}
+// Filters `$exception` events for requests 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 happened to be fetching, so each one fingerprints against a different stack
+// and files its own error tracking issue. `NetworkError` with reason `network` is deliberately kept:
+// a request that failed while the user was online and staying put is worth seeing. Exported for
+// unit testing.
+export function dropUnactionableNetworkExceptions<
+ T extends { event?: string; properties?: Record<string, any> } | null,
+>(event: T): T | null {
+ if (!event || event.event !== '$exception') {
+ return event
+ }
+ const list = (event.properties?.$exception_list ?? []) as Array<{ type?: string; value?: string }>
+ if (
+ list.some(
+ (ex) =>
+ ex?.type === 'NetworkError' && ex?.value != null && UNACTIONABLE_NETWORK_ERROR_MESSAGES.has(ex.value)
+ )
+ ) {
+ return null
+ }
+ return event
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface selfReadOnlyModeLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
@@ -191,11 +216,14 @@ export const selfReadOnlyModeLogic = kea<selfReadOnlyModeLogicType>([
setReadOnlyNotifier((method) => actions.notifyBlocked(method))
// Central error-tracking filter chain — drops `$exception` events for a ReadOnlyModeError
- // (a block by design) and for the handled auth gates (2FA setup/verify, re-auth). Catches
- // direct captures *and* wrapped errors (`new Error('...', { cause: readOnlyErr })`). This
- // logic mounts in the authenticated app, where every gated request happens, and no other
- // code that runs there sets `before_send`, so we own this config slot.
- posthog.set_config({ before_send: [dropReadOnlyExceptions, dropHandledAuthGateExceptions] })
+ // (a block by design), for the handled auth gates (2FA setup/verify, re-auth), and for the
+ // network failures that only describe the client's situation. Catches direct captures *and*
+ // wrapped errors (`new Error('...', { cause: readOnlyErr })`). This logic mounts in the
+ // authenticated app, where every gated request happens, and no other code that runs there
+ // sets `before_send`, so we own this config slot.
+ posthog.set_config({
+ before_send: [dropReadOnlyExceptions, dropHandledAuthGateExceptions, dropUnactionableNetworkExceptions],
+ })
// The user-facing toast for blocked writes is shown by the standard
// `e instanceof ApiError → lemonToast.error(e.detail)` pattern that
diff --git a/frontend/src/lib/api-error.ts b/frontend/src/lib/api-error.ts
index 4f769531808b..d99784fd69a4 100644
--- a/frontend/src/lib/api-error.ts
+++ b/frontend/src/lib/api-error.ts
@@ -83,3 +83,48 @@ export class ApiError extends Error {
return 'later'
}
}
+
+/**
+ * Why a request never reached the server. `offline` and `navigating` describe the state of the
+ * client rather than a fault in the request path, so they are dropped before they reach error
+ * tracking (see `dropUnactionableNetworkExceptions`). `network` is the residue that is worth
+ * looking at: an ad blocker, a misconfigured reverse proxy, DNS, a CDN, or our own edge.
+ */
+export type NetworkFailureReason = 'offline' | 'navigating' | 'network'
+
+/**
+ * One fixed message per reason. Two constraints meet here. The browser's own wording varies by
+ * engine ("Failed to fetch", "Load failed", "NetworkError when attempting to fetch resource."),
+ * and the automatic unhandled-rejection capture carries no custom properties, so the message is
+ * the only place the reason can travel to `before_send` and to error tracking grouping rules.
+ */
+export const NETWORK_ERROR_MESSAGES = {
+ offline: 'Network request failed: device is offline',
+ navigating: 'Network request failed: page was closing',
+ network: 'Network request failed',
+} as const satisfies Record<NetworkFailureReason, string>
+
+/** The reasons that are never a defect, so filing them as error tracking issues only adds noise. */
+export const UNACTIONABLE_NETWORK_ERROR_MESSAGES: ReadonlySet<string> = new Set([
+ NETWORK_ERROR_MESSAGES.offline,
+ NETWORK_ERROR_MESSAGES.navigating,
+])
+
+/**
+ * A request the browser never completed, so there is no HTTP status to react to. `status` is left
+ * undefined on purpose: recovery paths across the app read `status === undefined` as "transient,
+ * may be retried" (for example `inviteSignupLogic` and `sourcesDataLogic`), and a placeholder like
+ * 0 would make them treat a connectivity blip as a client error.
+ */
+export class NetworkError extends ApiError {
+ constructor(
+ public reason: NetworkFailureReason,
+ cause?: unknown
+ ) {
+ super(NETWORK_ERROR_MESSAGES[reason])
+ // Sets the `type` posthog-js reports in `$exception_list`, which is what
+ // `dropUnactionableNetworkExceptions` and error tracking grouping rules match on.
+ this.name = 'NetworkError'
+ this.cause = cause
+ }
+}
diff --git a/frontend/src/lib/api.test.ts b/frontend/src/lib/api.test.ts
index 0bbeb3546795..29db144c0576 100644
--- a/frontend/src/lib/api.test.ts
+++ b/frontend/src/lib/api.test.ts
@@ -1,7 +1,7 @@
import * as fetchEventSourceModule from '@microsoft/fetch-event-source'
import posthog from 'posthog-js'
-import api, { ApiConfig, ApiError, ApiRequest } from 'lib/api'
+import api, { ApiConfig, ApiError, ApiRequest, NetworkError } from 'lib/api'
import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
import { NodeKind } from '~/queries/schema/schema-general'
@@ -343,6 +343,91 @@ describe('API helper', () => {
})
})
+ describe('requests that never reach the server', () => {
+ // `pagehide` sets a module-level flag in lib/api, so clear it after every case instead of
+ // letting one test's simulated navigation classify the next test's failure.
+ afterEach(() => {
+ window.dispatchEvent(new Event('pageshow'))
+ window.localStorage.removeItem(OAUTH_SESSION_KEY)
+ })
+
+ it.each([
+ ['offline', false, 'Network request failed: device is offline'],
+ ['network', true, 'Network request failed'],
+ ])('classifies a fetch rejection as %s', async (reason, onLine, message) => {
+ Object.defineProperty(window.navigator, 'onLine', { value: onLine, configurable: true })
+ fakeFetch.mockRejectedValue(new TypeError('Failed to fetch'))
+
+ const error = await api.get('api/environments/2/insights').catch((e) => e)
+
+ expect(error).toBeInstanceOf(NetworkError)
+ expect(error.reason).toBe(reason)
+ // The message is the only channel the reason has: the automatic unhandled-rejection
+ // capture carries no custom properties, so `before_send` and grouping rules match on it
+ expect(error.message).toBe(message)
+ // Recovery paths across the app read `status === undefined` as "transient, may be retried"
+ expect(error.status).toBeUndefined()
+ })
+
+ it('classifies a fetch rejection during page teardown as navigating', async () => {
+ window.dispatchEvent(new Event('pagehide'))
+ fakeFetch.mockRejectedValue(new TypeError('Failed to fetch'))
+
+ const error = await api.get('api/environments/2/insights').catch((e) => e)
+
+ expect(error).toMatchObject({ reason: 'navigating' })
+ })
+
+ it('reports the failure as a client_request_failure naming the endpoint', async () => {
+ fakeFetch.mockRejectedValue(new TypeError('Failed to fetch'))
+
+ await api.get('api/environments/2/insights').catch(() => null)
+
+ expect(posthog.capture).toHaveBeenCalledWith(
+ 'client_request_failure',
+ expect.objectContaining({
+ pathname: '/api/environments/2/insights/',
+ method: 'GET',
+ // 0 keeps these separable from failures that did come back with an HTTP status
+ status: 0,
+ failure_reason: 'network',
+ })
+ )
+ })
+
+ it('still classifies the failure when the request URL cannot be parsed', async () => {
+ // `backendHost` comes straight from localStorage, so an out-of-range port reaches the
+ // request URL, and `fetch` rejects it with a TypeError. Deriving the pathname must not
+ // throw on the same URL, which would replace the classified failure with a crash.
+ window.localStorage.setItem(
+ OAUTH_SESSION_KEY,
+ JSON.stringify({
+ backendHost: 'https://:99999',
+ clientId: 'client',
+ accessToken: 'oauth-token',
+ refreshToken: 'refresh',
+ expiresAt: 9999999999999,
+ })
+ )
+ fakeFetch.mockRejectedValue(new TypeError('Failed to parse URL'))
+
+ const error = await api.get('/api/projects/2/insights/').catch((e) => e)
+
+ expect(error).toBeInstanceOf(NetworkError)
+ })
+
+ it('leaves a throw that is not a fetch failure as an unclassified ApiError', async () => {
+ // A real fault in the request path must not be relabelled as connectivity, or
+ // `dropUnactionableNetworkExceptions` would filter it out of error tracking.
+ fakeFetch.mockRejectedValue(new Error('the fetcher itself broke'))
+
+ const error = await api.get('api/environments/2/insights').catch((e) => e)
+
+ expect(error).toBeInstanceOf(ApiError)
+ expect(error).not.toBeInstanceOf(NetworkError)
+ })
+ })
+
describe('organizationFeatureFlags', () => {
it('builds correct URL for organization feature flags', () => {
const apiRequest = new ApiRequest()
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 713fa34631a6..f7a821e664e4 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -7,7 +7,7 @@ import { encodeParams } from 'kea-router'
export type { EventSourceMessage } from '@microsoft/fetch-event-source'
import posthog from 'posthog-js'
-import { ApiError } from 'lib/api-error'
+import { ApiError, NetworkError, type NetworkFailureReason } from 'lib/api-error'
import { ActivityLogProps } from 'lib/components/ActivityLog/ActivityLog'
import { ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'
import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
@@ -320,7 +320,7 @@ export interface ApiMethodOptions {
headers?: Record<string, any>
}
-export { ApiError }
+export { ApiError, NetworkError }
export class RateLimitError extends Error {
constructor(public retryAfterSeconds: number) {
@@ -7492,6 +7492,62 @@ const api = {
const warnedSharedViewLeaks = new Set<string>()
+/**
+ * Tracks whether the document is on its way out. A browser cancels every in-flight `fetch` when it
+ * tears the document down, and the rejection it hands back is the same bare `TypeError` a real
+ * connectivity failure produces, so this flag is the only way `handleFetch` can tell the two apart.
+ * `pagehide` also fires when the page enters the back/forward cache, hence the reset on `pageshow`:
+ * a restored page is live again and its requests are expected to succeed.
+ */
+let documentUnloading = false
+if (typeof window !== 'undefined') {
+ window.addEventListener('pagehide', () => {
+ documentUnloading = true
+ })
+ window.addEventListener('pageshow', () => {
+ documentUnloading = false
+ })
+}
+
+/**
+ * A malformed URL is one of the things `fetch` rejects with a `TypeError` for, and `new URL` would
+ * throw on the same input. Without the fallback that throw escapes from inside the failure path and
+ * replaces the classified `NetworkError` with a bare crash, losing the request that caused it.
+ */
+function requestPathname(url: string): string {
+ try {
+ return new URL(url, location.origin).pathname
+ } catch {
+ return url
+ }
+}
+
+function classifyNetworkFailure(): NetworkFailureReason {
+ if (documentUnloading) {
+ return 'navigating'
+ }
+ if (typeof navigator !== 'undefined' && navigator.onLine === false) {
+ return 'offline'
+ }
+ return 'network'
+}
+
+function captureClientRequestFailure(properties: {
+ pathname: string
+ method: string
+ duration: number
+ /** 0 for a request that never reached the server, so network failures are separable from HTTP ones. */
+ status: number
+ is_shared_view: boolean
+ failure_reason?: NetworkFailureReason
+}): void {
+ // when used inside the posthog toolbar, `posthog.capture` isn't loaded
+ // check if the function is available before calling it.
+ if (posthog.capture) {
+ posthog.capture('client_request_failure', properties)
+ }
+}
+
async function handleFetch(
url: string,
method: string,
@@ -7514,6 +7570,24 @@ async function handleFetch(
if (error && (error as any).name === 'AbortError') {
throw error
}
+ // `fetch` rejects with a `TypeError` when the request never reached the server. Classifying it
+ // here is what makes the failure legible: the call site only knows "something threw", while
+ // this frame still knows which endpoint was in flight, how long it ran, and whether the client
+ // was offline or going away. Anything else thrown by the fetcher is a genuine fault in the
+ // request path, so it keeps surfacing as an unclassified `ApiError` rather than being
+ // relabelled as a connectivity problem and filtered out of error tracking.
+ if (error instanceof TypeError) {
+ const reason = classifyNetworkFailure()
+ captureClientRequestFailure({
+ pathname: requestPathname(url),
+ method,
+ duration: new Date().getTime() - startTime,
+ status: 0,
+ is_shared_view: isSharedView(),
+ failure_reason: reason,
+ })
+ throw new NetworkError(reason, error)
+ }
throw new ApiError(error as any, response?.status)
}
@@ -7530,17 +7604,13 @@ async function handleFetch(
const duration = new Date().getTime() - startTime
const pathname = new URL(url, location.origin).pathname
const inSharedView = isSharedView()
- // when used inside the posthog toolbar, `posthog.capture` isn't loaded
- // check if the function is available before calling it.
- if (posthog.capture) {
- posthog.capture('client_request_failure', {
- pathname,
- method,
- duration,
- status: response.status,
- is_shared_view: inSharedView,
- })
- }
+ captureClientRequestFailure({
+ pathname,
+ method,
+ duration,
+ status: response.status,
+ is_shared_view: inSharedView,
+ })
if (inSharedView && (response.status === 401 || response.status === 403)) {
const leakKey = `${method} ${pathname}`
if (!warnedSharedViewLeaks.has(leakKey)) {