: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): stop filing handled API responses as issues (#84501)
Carlos Marchal7689446fd5b1
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex 34abc4ac5b43..85d92c474ecf 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -8,7 +8,7 @@ import { waitForPlugin } from 'kea-waitfor'import { windowValuesPlugin } from 'kea-window-values'import posthog from 'posthog-js'-import { isAccessDeniedError, isApprovalRequiredError } from 'lib/api-error'+import { isAccessDeniedError, shouldReportApiFailure } from 'lib/api-error'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import {addProjectIdIfMissing,@@ -70,14 +70,6 @@ generic toast would be a second one. Owned by featureFlagLogic's saveFeatureFlag*/const DUPLICATE_KEY_SELF_HANDLED = new Set(['saveFeatureFlag'])-/*-Transient gateway/proxy errors. These are infrastructure-level failures (the gateway can't-reach the backend), not application bugs, so we still toast the user a retryable failure but-don't report them to error tracking — otherwise sporadic 5xxs surface as noisy code-regression-issues. 500 is intentionally excluded: those are genuine backend exceptions worth capturing.-*/-const TRANSIENT_GATEWAY_STATUSES = [502, 503, 504]-interface InitKeaProps {state?: Record<string, any>routerHistory?: any@@ -211,9 +203,7 @@ export function initKea({if (!errorsSilenced) {console.error({ error, reducerKey, actionKey })}- // An approvals 409 is expected control flow (a change request was created, or one- // is already pending) surfaced to the user by the approvals UI, not a failure.- if (!TRANSIENT_GATEWAY_STATUSES.includes(error?.status) && !isApprovalRequiredError(error)) {+ if (shouldReportApiFailure(error)) {posthog.captureException(error)}},diff --git a/frontend/src/lib/api-error.test.ts b/frontend/src/lib/api-error.test.tsindex ea3801aaa69c..77d9a8a37594 100644--- a/frontend/src/lib/api-error.test.ts+++ b/frontend/src/lib/api-error.test.ts@@ -1,4 +1,4 @@-import { ApiError, isTransientServerError } from './api-error'+import { ApiError, isTransientServerError, shouldReportApiFailure } from './api-error'describe('api-error', () => {describe('ApiError.fromResponse', () => {@@ -81,4 +81,42 @@ describe('api-error', () => {expect(isTransientServerError(error)).toBe(false)})})++ describe('shouldReportApiFailure', () => {+ it.each([+ // Handled by something else, so reporting them only buries real crashes.+ ['a 401 the session check logs the user out of', { status: 401 }, false],+ ['an access-denied 403', { status: 403, code: 'permission_denied' }, false],+ ['a 2FA setup gate', { status: 403, code: 'two_factor_setup_required' }, false],+ ['a 2FA verification gate', { status: 403, code: 'two_factor_verification_required' }, false],+ ['a re-auth gate', { status: 403, code: 'sensitive_action_required_reauth' }, false],+ ['an approvals 409', { status: 409, data: { change_request_id: 'abc' } }, false],+ ['a 502', { status: 502 }, false],+ ['a 503', { status: 503 }, false],+ ['a 504', { status: 504 }, false],+ // Only the listed codes are excused: a 403 the app does not recover from is still a+ // signal, and read-only mode is dropped later by its own `before_send` filter.+ ['a 403 with no code', { status: 403 }, true],+ ['a read-only-mode 403', { status: 403, code: 'read_only_blocked' }, true],+ ['a 409 that is not an approvals gate', { status: 409, data: {} }, true],+ ['a 500 backend exception', { status: 500 }, true],+ ['a 400 validation error', { status: 400 }, true],+ ['a 404', { status: 404 }, true],+ // No HTTP response to excuse the failure.+ ['an error with no status', { message: 'boom' }, true],+ ['a thrown string', 'went wrong', true],+ ['null', null, true],+ ])('decides whether to report %s', (_, error, expected) => {+ expect(shouldReportApiFailure(error)).toBe(expected)+ })++ // The hand-written cases above use literals; this proves the shape `fromResponse` actually+ // builds (`code` lifted off the response body) classifies the same way.+ it('reads the code off a constructed ApiError', async () => {+ const body = { detail: "You don't have access to the project.", code: 'permission_denied' }+ const error = await ApiError.fromResponse(new Response(JSON.stringify(body), { status: 403 }))++ expect(shouldReportApiFailure(error)).toBe(false)+ })+ })})diff --git a/frontend/src/lib/api-error.ts b/frontend/src/lib/api-error.tsindex 62fc5a79bc10..c6c00b80b666 100644--- a/frontend/src/lib/api-error.ts+++ b/frontend/src/lib/api-error.ts@@ -15,6 +15,13 @@ export function isApprovalRequiredError(error: { status?: number; data?: any } |return error?.status === 409 && Boolean(error?.data?.change_request_id)}+/** Infrastructure-level failures where the gateway couldn't reach the backend. */+const TRANSIENT_GATEWAY_STATUSES: ReadonlySet<number> = new Set([502, 503, 504])++function isTransientGatewayStatus(status: number | undefined): boolean {+ return status !== undefined && TRANSIENT_GATEWAY_STATUSES.has(status)+}+/*** A transient gateway failure (502/503/504) rather than anything the caller did wrong. These* often arrive with an empty body (so `detail` is null) and usually succeed on retry, so a@@ -23,7 +30,58 @@ export function isApprovalRequiredError(error: { status?: number; data?: any } |* bug, so it should keep surfacing its `detail` and reach error tracking.*/export function isTransientServerError(error: unknown): boolean {- return error instanceof ApiError && (error.status === 502 || error.status === 503 || error.status === 504)+ return error instanceof ApiError && isTransientGatewayStatus(error.status)+}++/** The 403 gates `apiStatusLogic` recovers from, keyed by the DRF `code` the backend sends. */+const HANDLED_AUTH_GATE_CODES: ReadonlySet<string> = new Set([+ 'two_factor_setup_required',+ 'two_factor_verification_required',+ 'sensitive_action_required_reauth',+])++/**+ * Whether a failed request is worth filing as an error tracking issue. A response the app asked+ * for and recovers from itself is not a defect, and reporting it buries the ones that are: every+ * `ApiError` is built in this file, so they all share one stack, and grouping ignores the message+ * once that stack resolves, which lands a handled 401 in the same issue as a genuine crash.+ *+ * Left unreported, because something else already resolves them for the user:+ * - 401 — an authentication state rather than a crash. `apiStatusLogic` re-checks the session and+ * logs the user out, best-effort: it bails while impersonating (where `ImpersonationNotice`+ * offers re-impersonation instead), before the user has loaded, and within 10s of its last check.+ * - 403 `permission_denied` — the sceneLogic gates render the AccessDenied scene.+ * - 403 auth gates — `apiStatusLogic` opens 2FA setup, re-verification, or a re-auth prompt.+ * - 409 carrying a `change_request_id` — the approvals UI shows the change request it created.+ * - 502/503/504 — the gateway couldn't reach the backend, so application code is not at fault.+ *+ * Each of these still toasts wherever it did before, and `client_request_failure` still records+ * every non-OK response with its status and pathname, so failure rates stay queryable even where+ * no recovery runs. That event is also the better record, since an exception raised here cannot say+ * which endpoint failed: every `ApiError` shares this file's stack.+ *+ * A plain 500 stays reportable on purpose, being a genuine backend exception, and so does anything+ * without an HTTP status (a thrown string, a bare `Error`) — there is no response to excuse it.+ */+export function shouldReportApiFailure(error: unknown): boolean {+ if (error === null || typeof error !== 'object') {+ return true+ }+ const failure = error as { status?: number; code?: string | null; data?: any }+ const status = typeof failure.status === 'number' ? failure.status : undefined+ if (status === undefined) {+ return true+ }+ if (status === 401 || isTransientGatewayStatus(status)) {+ return false+ }+ if (isAccessDeniedError(failure)) {+ return false+ }+ if (status === 403 && failure.code != null && HANDLED_AUTH_GATE_CODES.has(failure.code)) {+ return false+ }+ return !isApprovalRequiredError(failure)}export class ApiError extends Error {