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(frontend): stop API failures reading as "Error: [object Object]" (#102026)

posthog[bot]355545274194
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.ts
index e9723e064bcf..61dfe5b0a13d 100644
--- a/frontend/src/initKea.ts
+++ b/frontend/src/initKea.ts
@@ -58,6 +58,9 @@ const ERROR_FILTER_ALLOW_LIST = [
'loadMonitoringSeries', // The managed warehouse Monitoring tab renders its own partial/error state
'loadInstrumentationChecklist', // AI observability hides its checklist entirely rather than accusing a project on data it could not read
'loadFullEmail', // Its failure listener shows a retry toast and closes the modal
+ 'addToPlaylist', // The replay collection popover toasts its own add failure
+ 'removeFromPlaylist', // The replay collection popover toasts its own remove failure
+ 'onPinnedChange', // The collection scene toasts its own pin/unpin failure
'draftScannerFromGoal', // replayScannerLogic's failure listener toasts and routes back to the goal questions
'loadRunDiff', // The Wizard run drawer renders its own diff error banner with a retry
'loadRunArtifacts', // The Wizard run drawer renders its own artifact error banner with a retry
diff --git a/frontend/src/lib/api-error.ts b/frontend/src/lib/api-error.ts
index c517b05392b8..68dd0190b92c 100644
--- a/frontend/src/lib/api-error.ts
+++ b/frontend/src/lib/api-error.ts
@@ -211,6 +211,24 @@ export function shouldReportApiFailure(error: unknown): boolean {
return !isApprovalRequiredError(failure)
}
+/**
+ * The readable message a failure carries, whether it arrived as a parsed error response body or as
+ * a value something in the request path threw. Returns undefined when nothing readable is there, so
+ * the caller falls back to its own wording instead of printing `[object Object]`.
+ */
+export function readableErrorMessage(error: unknown): string | undefined {
+ if (typeof error === 'string') {
+ return error || undefined
+ }
+ if (error === null || typeof error !== 'object') {
+ return undefined
+ }
+ const failure = error as Record<string, unknown>
+ return [failure.error, failure.detail, failure.message].find(
+ (value): value is string => typeof value === 'string' && value.length > 0
+ )
+}
+
export class ApiError extends Error {
/** Django REST Framework `detail` - used in downstream error handling. */
detail: string | null
@@ -250,12 +268,9 @@ export class ApiError extends Error {
}
}
- const errorData = data && typeof data === 'object' ? (data as Record<string, unknown>) : null
- const responseMessage = [errorData?.error, errorData?.detail, errorData?.message].find(
- (value): value is string => typeof value === 'string'
- )
+ const errorData = data && typeof data === 'object' ? data : null
- return new ApiError(responseMessage || fallbackMessage, response.status, response.headers, data)
+ return new ApiError(readableErrorMessage(errorData) || fallbackMessage, response.status, response.headers, data)
}
/**
diff --git a/frontend/src/lib/api.test.ts b/frontend/src/lib/api.test.ts
index a1f357c855a5..5e84058d6f0f 100644
--- a/frontend/src/lib/api.test.ts
+++ b/frontend/src/lib/api.test.ts
@@ -483,6 +483,32 @@ describe('API helper', () => {
expect(error).toBeInstanceOf(ApiError)
expect(error).not.toBeInstanceOf(NetworkError)
+ expect(error.message).toBe('the fetcher itself broke')
+ })
+
+ it('keeps a thrown object readable instead of stringifying it into the message', async () => {
+ // The caught value used to be passed as the `message`, so an object read back as
+ // "[object Object]" wherever the app prints one, and `detail` and `code` came back null.
+ const thrown = { detail: 'You lack access to this collection.', code: 'permission_denied' }
+ fakeFetch.mockRejectedValue(thrown)
+
+ const error = await api.get('api/environments/2/insights').catch((e) => e)
+
+ expect(error.message).toBe('You lack access to this collection.')
+ expect(error.code).toBe('permission_denied')
+ expect(error.data).toBe(thrown)
+ })
+
+ it('keeps the original stack as the cause', async () => {
+ // Every ApiError is built in one file, so they share its stack. posthog-js walks `cause`
+ // and reports the chained frames; it never reads `data`, so only this keeps a reported
+ // request-path fault locatable.
+ const thrown = new Error('the fetcher itself broke')
+ fakeFetch.mockRejectedValue(thrown)
+
+ const error = await api.get('api/environments/2/insights').catch((e) => e)
+
+ expect(error.cause).toBe(thrown)
})
})
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 5ee0f7bf13f7..03399c259cc2 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -7,7 +7,13 @@ import { encodeParams } from 'kea-router'
export type { EventSourceMessage } from '@microsoft/fetch-event-source'
import posthog from 'posthog-js'
-import { ApiError, BROWSER_FETCH_FAILURE_MESSAGES, NetworkError, type NetworkFailureReason } from 'lib/api-error'
+import {
+ ApiError,
+ BROWSER_FETCH_FAILURE_MESSAGES,
+ NetworkError,
+ type NetworkFailureReason,
+ readableErrorMessage,
+} from 'lib/api-error'
import { ActivityLogProps } from 'lib/components/ActivityLog/ActivityLog'
import { ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'
import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
@@ -7569,7 +7575,14 @@ async function handleFetch(
})
throw new NetworkError(reason, error)
}
- throw new ApiError(error as any, response?.status)
+ // The caught value is the failure, not its message: passing it as `message` stringifies an
+ // object to "[object Object]" and leaves `detail`, `code` and `data` empty, so neither the
+ // user nor support can read what went wrong. `cause` carries the original stack, which is the
+ // only frame naming where in the request path the fault came from - every `ApiError` shares
+ // this one.
+ const failure = new ApiError(readableErrorMessage(error), response?.status, response?.headers, error)
+ failure.cause = error
+ throw failure
}
// Standalone OAuth mode: a 401 likely means the access token expired — refresh once and retry.
diff --git a/frontend/src/scenes/session-recordings/player/playlist-popover/playlistPopoverLogic.test.ts b/frontend/src/scenes/session-recordings/player/playlist-popover/playlistPopoverLogic.test.ts
new file mode 100644
index 000000000000..e95878487182
--- /dev/null
+++ b/frontend/src/scenes/session-recordings/player/playlist-popover/playlistPopoverLogic.test.ts
@@ -0,0 +1,44 @@
+import { expectLogic } from 'kea-test-utils'
+
+import api from 'lib/api'
+import { ApiError } from 'lib/api-error'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { SessionRecordingPlaylistType } from '~/types'
+
+import { playlistPopoverLogic } from './playlistPopoverLogic'
+
+describe('playlistPopoverLogic', () => {
+ let logic: ReturnType<typeof playlistPopoverLogic.build>
+ const collection = { id: 1, short_id: 'abc', name: 'My collection' } as SessionRecordingPlaylistType
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:team/session_recording_playlists': { results: [], count: 0 },
+ },
+ })
+ initKeaTests()
+ jest.spyOn(lemonToast, 'error').mockImplementation(() => '')
+ logic = playlistPopoverLogic({ sessionRecordingId: 'rec-1', playerKey: 'test' })
+ logic.mount()
+ })
+
+ // A status-less failure is what `handleFetch` throws when the request path itself faults, and
+ // the generic loader toast in initKea only fires when `status` is set. Without these listeners
+ // the popover row completes nothing and says nothing.
+ it.each([
+ ['addToPlaylist', 'addRecordingToPlaylist' as const, 'Failed to add to collection'],
+ ['removeFromPlaylist', 'removeRecordingFromPlaylist' as const, 'Failed to remove from collection'],
+ ])('toasts once when %s fails without a status', async (action, apiMethod, expectedPrefix) => {
+ jest.spyOn(api.recordings, apiMethod).mockRejectedValue(new ApiError('You cannot edit this collection.'))
+
+ logic.actions[action as 'addToPlaylist' | 'removeFromPlaylist'](collection)
+
+ await expectLogic(logic).toDispatchActions([`${action}Failure`])
+ expect(lemonToast.error).toHaveBeenCalledTimes(1)
+ expect(lemonToast.error).toHaveBeenCalledWith(`${expectedPrefix}: You cannot edit this collection.`)
+ })
+})
diff --git a/frontend/src/scenes/session-recordings/player/playlist-popover/playlistPopoverLogic.ts b/frontend/src/scenes/session-recordings/player/playlist-popover/playlistPopoverLogic.ts
index 8379ba3689f5..1b68a1fd8754 100644
--- a/frontend/src/scenes/session-recordings/player/playlist-popover/playlistPopoverLogic.ts
+++ b/frontend/src/scenes/session-recordings/player/playlist-popover/playlistPopoverLogic.ts
@@ -4,6 +4,7 @@ import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from
import { lazyLoaders, loaders } from 'kea-loaders'
import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { toParams } from 'lib/utils/url'
import {
SessionRecordingPlayerLogicProps,
@@ -344,6 +345,12 @@ export const playlistPopoverLogic = kea<playlistPopoverLogicType>([
},
})),
listeners(({ actions, values }) => ({
+ addToPlaylistFailure: ({ error }) => {
+ lemonToast.error(`Failed to add to collection: ${error}`)
+ },
+ removeFromPlaylistFailure: ({ error }) => {
+ lemonToast.error(`Failed to remove from collection: ${error}`)
+ },
setSearchQuery: () => {
actions.loadPlaylists()
},
diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic.test.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic.test.ts
index 080680309e9a..4f0ebcf70956 100644
--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic.test.ts
+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic.test.ts
@@ -1,12 +1,22 @@
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { HttpResponse } from 'msw'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { sessionRecordingsPlaylistSceneLogic } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic'
import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
+import { SessionRecordingType } from '~/types'
+
+jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
+ lemonToast: {
+ error: jest.fn(),
+ success: jest.fn(),
+ },
+}))
describe('sessionRecordingsPlaylistSceneLogic', () => {
let logic: ReturnType<typeof sessionRecordingsPlaylistSceneLogic.build>
@@ -95,6 +105,24 @@ describe('sessionRecordingsPlaylistSceneLogic', () => {
})
})
+ describe('pinning a recording', () => {
+ it('reports a pin request that fails without a status', async () => {
+ useMocks({
+ post: {
+ '/api/projects/:team/session_recording_playlists/:id/recordings/:recordingId': () =>
+ HttpResponse.error(),
+ },
+ })
+ logic.mount()
+
+ logic.actions.onPinnedChange({ id: 'rec_1' } as SessionRecordingType, true)
+
+ await expectLogic(logic).toDispatchActions(['onPinnedChangeFailure'])
+ expect(lemonToast.error).toHaveBeenCalledWith(expect.stringContaining('Failed to update collection'))
+ expect(logic.values.pinnedRecordings).toBeNull()
+ })
+ })
+
describe('update playlist', () => {
it('set new filter then update playlist', () => {
logic.mount()
diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic.ts
index b73142236dcb..88e46f44a133 100644
--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic.ts
+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistSceneLogic.ts
@@ -4,6 +4,7 @@ import { loaders } from 'kea-loaders'
import { beforeUnload, combineUrl, router, urlToAction } from 'kea-router'
import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { sceneLogic } from 'scenes/sceneLogic'
@@ -315,6 +316,9 @@ export const sessionRecordingsPlaylistSceneLogic = kea<sessionRecordingsPlaylist
})),
listeners(({ actions, values, props }) => ({
+ onPinnedChangeFailure: ({ error }) => {
+ lemonToast.error(`Failed to update collection: ${error}`)
+ },
getPlaylistSuccess: ({ playlist }) => {
if (playlist?.type === 'filters') {
// The load can resolve after the user has already navigated elsewhere (e.g. to Replay