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.

refactor(ux): centralise read-only error suppression (#60069)

posthog[bot]48f815de8251
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.ts
index b0939fe9884d..8a80ca2b1baa 100644
--- a/frontend/src/initKea.ts
+++ b/frontend/src/initKea.ts
@@ -100,6 +100,12 @@ export function initKea({
formsPlugin,
loadersPlugin({
onFailure({ error, reducerKey, actionKey }: { error: any; reducerKey: string; actionKey: string }) {
+ // Read-only mode (`ReadOnlyModeError`) flows through this path unchanged:
+ // it extends `ApiError` with `status=403`, so the `!(isLoadAction && error.status === 403)`
+ // condition already suppresses the toast for load actions, and write actions
+ // get a toast with the read-only `detail` as the message. The
+ // `posthog.captureException` event is dropped by the central
+ // `before_send` filter in `selfReadOnlyModeLogic`.
// Toast if it's a fetch error or a specific API update error
const isLoadAction = typeof actionKey === 'string' && /^(load|get|fetch)[A-Z]/.test(actionKey)
if (
diff --git a/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.test.ts b/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.test.ts
new file mode 100644
index 000000000000..9f5929715270
--- /dev/null
+++ b/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.test.ts
@@ -0,0 +1,56 @@
+import { dropReadOnlyExceptions } from './selfReadOnlyModeLogic'
+
+describe('dropReadOnlyExceptions', () => {
+ it('passes non-exception events through unchanged', () => {
+ const event = { event: '$pageview', properties: { $current_url: '/foo' } }
+ expect(dropReadOnlyExceptions(event)).toBe(event)
+ })
+
+ it('passes $exception events without ReadOnlyModeError through', () => {
+ const event = {
+ event: '$exception',
+ properties: {
+ $exception_list: [{ type: 'TypeError', value: 'x is not a function' }],
+ },
+ }
+ expect(dropReadOnlyExceptions(event)).toBe(event)
+ })
+
+ it('drops $exception events whose top-level type is ReadOnlyModeError', () => {
+ const event = {
+ event: '$exception',
+ properties: {
+ $exception_list: [{ type: 'ReadOnlyModeError', value: 'You are in read-only mode' }],
+ },
+ }
+ expect(dropReadOnlyExceptions(event)).toBeNull()
+ })
+
+ it('drops wrapped errors where ReadOnlyModeError lives in the cause chain', () => {
+ // posthog-js serializes `new Error('wrapper', { cause: readOnlyErr })`
+ // by appending the cause to `$exception_list`. The filter walks the
+ // whole list so wrappers do not slip through.
+ const event = {
+ event: '$exception',
+ properties: {
+ $exception_list: [
+ { type: 'Error', value: 'reverseProxyCheckerLogic: query failed' },
+ { type: 'ReadOnlyModeError', value: 'You are in read-only mode' },
+ ],
+ },
+ }
+ expect(dropReadOnlyExceptions(event)).toBeNull()
+ })
+
+ it('tolerates missing properties and missing exception list', () => {
+ expect(dropReadOnlyExceptions({ event: '$exception' })).toEqual({ event: '$exception' })
+ expect(dropReadOnlyExceptions({ event: '$exception', properties: {} })).toEqual({
+ event: '$exception',
+ properties: {},
+ })
+ })
+
+ it('returns null when handed null (matching posthog-js before_send contract)', () => {
+ expect(dropReadOnlyExceptions(null)).toBeNull()
+ })
+})
diff --git a/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.ts b/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.ts
index a712bad7685f..df65678256b7 100644
--- a/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.ts
+++ b/frontend/src/layout/navigation/SelfReadOnlyNotice/selfReadOnlyModeLogic.ts
@@ -14,11 +14,21 @@ export const ESCALATION_OPTIONS = [
{ seconds: 300, label: 'Allow for 5 min' },
] as const
-const METHOD_TO_VERB: Record<string, string> = {
- POST: 'create',
- PUT: 'edit',
- PATCH: 'edit',
- DELETE: 'delete',
+// Filters `$exception` events whose chain contains a ReadOnlyModeError so the
+// read-only feature doesn't spam error tracking for blocks-by-design. The
+// chain walk catches wrapped errors (e.g. `new Error('...', { cause: e })`).
+// Exported for unit testing.
+export function dropReadOnlyExceptions<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 }>
+ if (list.some((ex) => ex?.type === 'ReadOnlyModeError')) {
+ return null
+ }
+ return event
}
export const selfReadOnlyModeLogic = kea<selfReadOnlyModeLogicType>([
@@ -77,12 +87,9 @@ export const selfReadOnlyModeLogic = kea<selfReadOnlyModeLogicType>([
lemonToast.info('Back to read-only mode.', { toastId: 'read-only-resumed' })
posthog.capture?.('read_only_ended')
},
+ // Analytics-only — the user-visible toast is no longer fired here. Catch blocks
+ // that match `e instanceof ApiError` already surface `ReadOnlyModeError.detail`.
notifyBlocked: ({ method }) => {
- const verb = METHOD_TO_VERB[method] ?? 'change'
- lemonToast.warning(
- `Read-only mode is on — that ${verb} was blocked. Ask Max or the MCP to make the change for you.`,
- { toastId: 'read-only-blocked' }
- )
posthog.capture?.('read_only_write_blocked', { method })
},
})),
@@ -94,10 +101,25 @@ export const selfReadOnlyModeLogic = kea<selfReadOnlyModeLogicType>([
// "path not in store" error on the next mutation.
setReadOnlyGetter(() => selfReadOnlyModeLogic.findMounted()?.values.isReadOnly ?? false)
setReadOnlyNotifier((method) => actions.notifyBlocked(method))
+
+ // Central error-tracking filter — drops any `$exception` event whose
+ // chain contains a ReadOnlyModeError. Catches direct captures *and*
+ // wrapped errors (`new Error('...', { cause: readOnlyErr })`). No
+ // existing code sets `before_send`, so we own this config slot.
+ posthog.set_config({ before_send: dropReadOnlyExceptions })
+
+ // The user-facing toast for blocked writes is shown by the standard
+ // `e instanceof ApiError → lemonToast.error(e.detail)` pattern that
+ // every write call-site already implements. ReadOnlyModeError extends
+ // ApiError and carries a method-specific `detail`, so no extra hook
+ // is needed.
}),
beforeUnmount(() => {
setReadOnlyGetter(null)
setReadOnlyNotifier(null)
+ // Releasing ownership of `before_send` — if PostHog adds another filter
+ // here in the future, it should compose rather than be clobbered.
+ posthog.set_config({ before_send: undefined })
}),
])
diff --git a/frontend/src/lib/api-error.ts b/frontend/src/lib/api-error.ts
new file mode 100644
index 000000000000..11e2094f8728
--- /dev/null
+++ b/frontend/src/lib/api-error.ts
@@ -0,0 +1,52 @@
+import { dayjs } from 'lib/dayjs'
+import { humanFriendlyDuration } from 'lib/utils'
+
+export class ApiError extends Error {
+ /** Django REST Framework `detail` - used in downstream error handling. */
+ detail: string | null
+ /** Django REST Framework `code` - used in downstream error handling. */
+ code: string | null
+ /** Django REST Framework `statusText` - used in downstream error handling. */
+ statusText: string | null
+ /** Django REST Framework `attr` - used in downstream error handling. */
+ attr: string | null
+
+ /** Link to external resources, e.g. stripe invoices */
+ link: string | null
+
+ constructor(
+ message?: string,
+ public status?: number,
+ public headers?: Headers,
+ public data?: any
+ ) {
+ message = message || `API request failed with status: ${status ?? 'unknown'}`
+ super(message)
+ this.statusText = data?.statusText || null
+ this.detail = data?.detail || null
+ this.code = data?.code || null
+ this.link = data?.link || null
+ this.attr = data?.attr || null
+ }
+
+ /**
+ * For when the API returned a 429 (Too Many Requests) error:
+ * If the `Retry-After` header is present, return a human-friendly duration, e.g. "in 4 hours", otherwise just "later".
+ * Return null for other status codes.
+ */
+ get formattedRetryAfter(): string | null {
+ if (this.status !== 429) {
+ return null
+ }
+ if (this.headers?.has('Retry-After')) {
+ const retryAfter = this.headers.get('Retry-After') as string
+ let secondsLeft = Number(retryAfter) // Let's assume we're dealing with an integer by default
+ if (isNaN(secondsLeft)) {
+ // Nope, here we're dealing with date in this format: Wed, 21 Oct 2015 07:28:00 GMT
+ secondsLeft = dayjs(retryAfter).diff(dayjs(), 'seconds')
+ }
+ return `in ${humanFriendlyDuration(secondsLeft, { maxUnits: 2 })}`
+ }
+ return 'later'
+ }
+}
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index fcd7c9ab13f5..98840b1b00bc 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -2,12 +2,12 @@ import { EventSourceMessage, fetchEventSource } from '@microsoft/fetch-event-sou
import { encodeParams } from 'kea-router'
import posthog from 'posthog-js'
+import { ApiError } from 'lib/api-error'
import { ActivityLogProps } from 'lib/components/ActivityLog/ActivityLog'
import { ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'
-import { dayjs } from 'lib/dayjs'
import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
import { assertNotReadOnly } from 'lib/readOnlyGuard'
-import { humanFriendlyDuration, objectClean, toParams } from 'lib/utils'
+import { objectClean, toParams } from 'lib/utils'
import { CohortCalculationHistoryResponse } from 'scenes/cohorts/cohortCalculationHistorySceneLogic'
import { EventSchema } from 'scenes/data-management/events/eventDefinitionSchemaLogic'
import { SchemaPropertyGroup } from 'scenes/data-management/schema/schemaManagementLogic'
@@ -304,55 +304,7 @@ export interface ApiMethodOptions {
headers?: Record<string, any>
}
-export class ApiError extends Error {
- /** Django REST Framework `detail` - used in downstream error handling. */
- detail: string | null
- /** Django REST Framework `code` - used in downstream error handling. */
- code: string | null
- /** Django REST Framework `statusText` - used in downstream error handling. */
- statusText: string | null
- /** Django REST Framework `attr` - used in downstream error handling. */
- attr: string | null
-
- /** Link to external resources, e.g. stripe invoices */
- link: string | null
-
- constructor(
- message?: string,
- public status?: number,
- public headers?: Headers,
- public data?: any
- ) {
- message = message || `API request failed with status: ${status ?? 'unknown'}`
- super(message)
- this.statusText = data?.statusText || null
- this.detail = data?.detail || null
- this.code = data?.code || null
- this.link = data?.link || null
- this.attr = data?.attr || null
- }
-
- /**
- * For when the API returned a 429 (Too Many Requests) error:
- * If the `Retry-After` header is present, return a human-friendly duration, e.g. "in 4 hours", otherwise just "later".
- * Return null for other status codes.
- */
- get formattedRetryAfter(): string | null {
- if (this.status !== 429) {
- return null
- }
- if (this.headers?.has('Retry-After')) {
- const retryAfter = this.headers.get('Retry-After') as string
- let secondsLeft = Number(retryAfter) // Let's assume we're dealing with an integer by default
- if (isNaN(secondsLeft)) {
- // Nope, here we're dealing with date in this format: Wed, 21 Oct 2015 07:28:00 GMT
- secondsLeft = dayjs(retryAfter).diff(dayjs(), 'seconds')
- }
- return `in ${humanFriendlyDuration(secondsLeft, { maxUnits: 2 })}`
- }
- return 'later'
- }
-}
+export { ApiError }
export class RateLimitError extends Error {
constructor(public retryAfterSeconds: number) {
diff --git a/frontend/src/lib/components/ReverseProxyChecker/reverseProxyCheckerLogic.test.ts b/frontend/src/lib/components/ReverseProxyChecker/reverseProxyCheckerLogic.test.ts
index a167be5508bc..6dfd8cf2572c 100644
--- a/frontend/src/lib/components/ReverseProxyChecker/reverseProxyCheckerLogic.test.ts
+++ b/frontend/src/lib/components/ReverseProxyChecker/reverseProxyCheckerLogic.test.ts
@@ -3,9 +3,6 @@ import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
-import api from 'lib/api'
-import { ReadOnlyModeError } from 'lib/readOnlyGuard'
-
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
@@ -107,41 +104,15 @@ describe('reverseProxyCheckerLogic', () => {
})
expect(toastErrorSpy).not.toHaveBeenCalled()
+ // The error is captured directly (not wrapped) so its type is preserved at the
+ // top of `$exception_list` — that lets the central `before_send` filter recognise
+ // `ReadOnlyModeError` without depending on cause-chain serialization.
expect(captureExceptionSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- message: expect.stringContaining('reverseProxyCheckerLogic: loadHasReverseProxy query failed'),
- })
+ expect.objectContaining({ status: 500 }),
+ expect.objectContaining({ posthog_source: 'reverseProxyCheckerLogic.loadHasReverseProxy' })
)
toastErrorSpy.mockRestore()
captureExceptionSpy.mockRestore()
})
-
- it('should not report read-only mode blocks to error tracking', async () => {
- // Regression: ReadOnlyModeError from loadHasReverseProxy must be swallowed,
- // otherwise every scene mount would spam error tracking via afterMount.
- //
- // We mock api.queryHogQL directly because /query is allow-listed in
- // readOnlyGuard, so setReadOnlyGetter wouldn't fire here.
- const queryHogQLSpy = jest.spyOn(api, 'queryHogQL').mockRejectedValue(new ReadOnlyModeError())
-
- const captureExceptionSpy = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined)
-
- try {
- logic.mount()
-
- await expectLogic(logic, () => {
- logic.actions.loadHasReverseProxy()
- })
- .toFinishAllListeners()
- .toMatchValues({
- hasReverseProxy: false,
- })
-
- expect(captureExceptionSpy).not.toHaveBeenCalled()
- } finally {
- captureExceptionSpy.mockRestore()
- queryHogQLSpy.mockRestore()
- }
- })
})
diff --git a/frontend/src/lib/components/ReverseProxyChecker/reverseProxyCheckerLogic.ts b/frontend/src/lib/components/ReverseProxyChecker/reverseProxyCheckerLogic.ts
index 2c0bf5b8e856..fdccb3444170 100644
--- a/frontend/src/lib/components/ReverseProxyChecker/reverseProxyCheckerLogic.ts
+++ b/frontend/src/lib/components/ReverseProxyChecker/reverseProxyCheckerLogic.ts
@@ -4,7 +4,6 @@ import posthog from 'posthog-js'
import api from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
-import { ReadOnlyModeError } from 'lib/readOnlyGuard'
import { sceneLogic } from 'scenes/sceneLogic'
import { hogql } from '~/queries/utils'
@@ -43,21 +42,18 @@ export const reverseProxyCheckerLogic = kea<reverseProxyCheckerLogicType>([
})
return !!res.results?.find((x) => !!x[0])
} catch (error) {
- // Read-only mode blocks every POST by design — afterMount fires on
- // every scene, so reporting these floods error tracking with expected
- // failures. Bail out without capturing.
- if (
- error instanceof ReadOnlyModeError ||
- (error as Error)?.cause instanceof ReadOnlyModeError
- ) {
- return values.hasReverseProxy
- }
// This check is advisory (used only to auto-complete a setup task).
// Swallow errors so kea-loaders does not surface a user-visible toast
// on every scene that mounts ProductSetupButton.
- posthog.captureException(
- new Error('reverseProxyCheckerLogic: loadHasReverseProxy query failed', { cause: error })
- )
+ //
+ // Capturing the original `error` directly (rather than wrapping it
+ // in `new Error('...', { cause })`) keeps the error type at the top
+ // of `$exception_list`, so the central `before_send` filter in
+ // `selfReadOnlyModeLogic` can drop `ReadOnlyModeError` without
+ // assuming posthog-js serialises the cause chain.
+ posthog.captureException(error, {
+ posthog_source: 'reverseProxyCheckerLogic.loadHasReverseProxy',
+ })
return values.hasReverseProxy
}
},
diff --git a/frontend/src/lib/readOnlyGuard.test.ts b/frontend/src/lib/readOnlyGuard.test.ts
index d7a72c85c978..82b333f82c52 100644
--- a/frontend/src/lib/readOnlyGuard.test.ts
+++ b/frontend/src/lib/readOnlyGuard.test.ts
@@ -1,3 +1,4 @@
+import { ApiError } from 'lib/api-error'
import {
assertNotReadOnly,
isReadOnly,
@@ -136,15 +137,29 @@ describe('readOnlyGuard', () => {
})
describe('ReadOnlyModeError', () => {
- it('has a sensible default detail message so caller error-fallback patterns produce truthful toasts', () => {
- const err = new ReadOnlyModeError()
- expect(err.detail).toBe('Read-only mode is on — change blocked. Use Max or the MCP to make this change.')
+ it('is an ApiError so existing catch blocks surface its detail', () => {
+ const err = new ReadOnlyModeError('POST')
+ expect(err).toBeInstanceOf(ApiError)
+ expect(err.status).toBe(403)
+ expect(err.code).toBe('read_only_blocked')
expect(err.name).toBe('ReadOnlyModeError')
})
- it('accepts a custom message', () => {
- const err = new ReadOnlyModeError('custom message')
- expect(err.message).toBe('custom message')
+ it.each([
+ ['POST', 'create'],
+ ['PUT', 'edit'],
+ ['PATCH', 'edit'],
+ ['DELETE', 'delete'],
+ ] as const)('personalises the detail for %s (verb: %s)', (method, verb) => {
+ const err = new ReadOnlyModeError(method)
+ expect(err.detail).toBe(
+ `Read-only mode is on — that ${verb} was blocked. Ask Max or the MCP to make the change for you.`
+ )
+ })
+
+ it('falls back to a generic detail when constructed without a method', () => {
+ const err = new ReadOnlyModeError()
+ expect(err.detail).toContain('that change was blocked')
})
})
diff --git a/frontend/src/lib/readOnlyGuard.ts b/frontend/src/lib/readOnlyGuard.ts
index 52769d50a332..05fd78a0397d 100644
--- a/frontend/src/lib/readOnlyGuard.ts
+++ b/frontend/src/lib/readOnlyGuard.ts
@@ -6,21 +6,36 @@
* (`selfReadOnlyModeLogic`) registers a getter that reads its current state.
*/
-export class ReadOnlyModeError extends Error {
- // Many call sites in the app catch api errors with the shape
- // `lemonToast.error(error.detail || 'Failed to ...')`. Without `detail`,
- // a read-only block would surface as the misleading fallback ("Failed to
- // launch experiment" etc.) on top of the dedicated read-only toast.
- // Setting `detail` here keeps that secondary toast at least truthful.
- detail = 'Read-only mode is on — change blocked. Use Max or the MCP to make this change.'
+import { ApiError } from 'lib/api-error'
- constructor(message = 'You are in read-only mode') {
- super(message)
+export type ReadOnlyMethod = 'PATCH' | 'PUT' | 'POST' | 'DELETE'
+
+const METHOD_TO_VERB: Record<ReadOnlyMethod, string> = {
+ POST: 'create',
+ PUT: 'edit',
+ PATCH: 'edit',
+ DELETE: 'delete',
+}
+
+function detailFor(method?: ReadOnlyMethod): string {
+ const verb = method ? METHOD_TO_VERB[method] : 'change'
+ return `Read-only mode is on — that ${verb} was blocked. Ask Max or the MCP to make the change for you.`
+}
+
+// Extends ApiError so the existing `e instanceof ApiError → lemonToast.error(e.detail)`
+// pattern surfaces the read-only message naturally, without per-callsite checks.
+// status=403 mirrors the Django response if this ever round-trips from the server.
+export class ReadOnlyModeError extends ApiError {
+ constructor(method?: ReadOnlyMethod) {
+ super('You are in read-only mode', 403, undefined, {
+ detail: detailFor(method),
+ code: 'read_only_blocked',
+ })
this.name = 'ReadOnlyModeError'
}
}
-type Notifier = (method: 'PATCH' | 'PUT' | 'POST' | 'DELETE') => void
+type Notifier = (method: ReadOnlyMethod) => void
type Getter = () => boolean
let getter: Getter | null = null
@@ -69,7 +84,7 @@ function isReadDisguisedAsWrite(url: string): boolean {
return READ_ONLY_ALLOWED_PATTERNS.some((pattern) => pattern.test(url))
}
-export function assertNotReadOnly(method: 'PATCH' | 'PUT' | 'POST' | 'DELETE', url: string): void {
+export function assertNotReadOnly(method: ReadOnlyMethod, url: string): void {
if (!isReadOnly()) {
return
}
@@ -77,5 +92,5 @@ export function assertNotReadOnly(method: 'PATCH' | 'PUT' | 'POST' | 'DELETE', u
return
}
notifier?.(method)
- throw new ReadOnlyModeError()
+ throw new ReadOnlyModeError(method)
}