: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(insights): stop the dashboard modal filing useless exceptions (#101352)
posthog[bot]04ae5a0627d3
diff --git a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.test.ts b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.test.tsindex a9809db8d780..041db48152d5 100644--- a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.test.ts+++ b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.test.ts@@ -2,7 +2,9 @@ import { MOCK_DEFAULT_USER } from 'lib/api.mock'import { expectLogic, partial } from 'kea-test-utils'+import { ApiError, NetworkError } from 'lib/api'import { FEATURE_FLAGS } from 'lib/constants'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'import { dashboardResult } from 'scenes/dashboard/dashboardLogic.testHelpers'@@ -12,7 +14,7 @@ import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { QueryBasedInsightModel } from '~/types'-import { addSavedInsightsModalLogic } from './addSavedInsightsModalLogic'+import { addSavedInsightsModalLogic, handleDashboardUpdateFailure } from './addSavedInsightsModalLogic'const createInsight = (id: number, name = 'test'): QueryBasedInsightModel =>({@@ -267,6 +269,100 @@ describe('addSavedInsightsModalLogic', () => {})})+ describe('dashboard membership updates', () => {+ const MESSAGES = { timedOut: 'Timed out', failed: 'Failed to add' }++ const insightOnDashboards = (dashboardIds: number[]): QueryBasedInsightModel =>+ ({+ ...createInsight(53),+ dashboard_tiles: dashboardIds.map((dashboardId, index) => ({+ id: index + 1,+ dashboard_id: dashboardId,+ deleted: false,+ })),+ }) as QueryBasedInsightModel++ it('keeps the other dashboards when adding', async () => {+ initKeaTests()+ const update = jest.spyOn(insightsApi, 'update').mockResolvedValue(createInsight(53))+ const logic = addSavedInsightsModalLogic()+ logic.mount()++ await expectLogic(logic, () =>+ logic.actions.addInsightToDashboard(insightOnDashboards([7, 8]), 9)+ ).toFinishAllListeners()++ expect(update).toHaveBeenCalledWith(53, { dashboards: [7, 8, 9] })++ logic.unmount()+ })++ it('keeps the other dashboards when removing', async () => {+ initKeaTests()+ const update = jest.spyOn(insightsApi, 'update').mockResolvedValue(createInsight(53))+ const logic = addSavedInsightsModalLogic()+ logic.mount()++ await expectLogic(logic, () =>+ logic.actions.removeInsightFromDashboard(insightOnDashboards([7, 8]), 8)+ ).toFinishAllListeners()++ expect(update).toHaveBeenCalledWith(53, { dashboards: [7] })++ logic.unmount()+ })++ it.each([+ [500, null],+ [403, "You don't have permission to remove insights from dashboard: 7"],+ ])('handles a %s instead of filing an unhandled rejection', async (status, detail) => {+ initKeaTests()+ const toastError = jest.spyOn(lemonToast, 'error').mockImplementation()+ jest.spyOn(insightsApi, 'update').mockRejectedValue(+ new ApiError('Non-OK response', status, undefined, { detail })+ )+ const logic = addSavedInsightsModalLogic()+ logic.mount()++ await expect(+ expectLogic(logic, () =>+ logic.actions.addInsightToDashboard(insightOnDashboards([7]), 9)+ ).toFinishAllListeners()+ ).resolves.toBeDefined()++ expect(toastError).toHaveBeenCalledWith(detail ?? 'Failed to add insight to dashboard')++ logic.unmount()+ })++ it.each([+ ['a 500 the backend answered with', () => new ApiError('Non-OK response', 500), 'Failed to add'],+ ['a request the browser dropped', () => new NetworkError('network'), 'Failed to add'],+ ])('consumes %s', (_label, buildError, expectedToast) => {+ const toastError = jest.spyOn(lemonToast, 'error').mockImplementation()++ expect(() => handleDashboardUpdateFailure(buildError(), MESSAGES)).not.toThrow()++ expect(toastError).toHaveBeenCalledWith(expectedToast)+ })++ it.each([+ ['the fetcher threw before a response arrived', () => new ApiError('the fetcher itself broke')],+ [+ 'a 2xx body would not parse',+ () => new ApiError('Malformed JSON response [PATCH /api/environments/2/insights/53/] (status 200)'),+ ],+ ])('rethrows a status-less failure, because %s and nothing else records it', (_label, buildError) => {+ const toastError = jest.spyOn(lemonToast, 'error').mockImplementation()+ const error = buildError()++ expect(() => handleDashboardUpdateFailure(error, MESSAGES)).toThrow(error)++ // The user sees the same sentence either way: the rethrow only restores the signal.+ expect(toastError).toHaveBeenCalledWith('Failed to add')+ })+ })+it('refreshes the mounted dashboard after adding an insight', async () => {initKeaTests()const dashboard = dashboardLogic({ id: 1, dashboard: dashboardResult(1, []) })diff --git a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.tsindex e5e166698aef..16403e33e41e 100644--- a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts+++ b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts@@ -2,8 +2,8 @@ import { MakeLogicType, actions, connect, events, kea, listeners, path, reducersimport { loaders } from 'kea-loaders'import posthog from 'posthog-js'-import api from 'lib/api'-import { isTransientServerError } from 'lib/api-error'+import api, { ApiError } from 'lib/api'+import { NetworkError, isTransientServerError } from 'lib/api-error'import { FEATURE_FLAGS } from 'lib/constants'import { Sorting } from 'lib/lemon-ui/LemonTable'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'@@ -41,6 +41,38 @@ interface InsightListParams {export const INSIGHTS_PER_PAGE = 15+/**+ * The dashboards an insight currently sits on. Read off the tiles rather than off the deprecated+ * `dashboards` field: a PATCH of `dashboards` replaces the whole membership, so the list has to come+ * from something the API still serves the web app.+ */+function currentDashboardIds(insight: QueryBasedInsightModel): number[] {+ return (insight.dashboard_tiles || []).filter((tile) => !tile.deleted).map((tile) => tile.dashboard_id)+}++/**+ * Tell the user a membership update failed, and rethrow only what is worth filing. The listener has+ * already rolled the toggle back, and every `ApiError` is built in one place, so an issue raised+ * from here shares its stack with every other API failure and cannot say which endpoint failed.+ * `client_request_failure` records the status and pathname instead.+ *+ * A failure with no status is the exception, because no such event was captured: the fetcher threw+ * before a response arrived, or a 2xx body would not parse. Its message already names the method and+ * the path, and the rethrow is the only signal it has. A `NetworkError` has no status either but+ * stays consumed: the fetch layer records it, and a request the browser dropped is not our defect.+ */+export function handleDashboardUpdateFailure(error: unknown, messages: { timedOut: string; failed: string }): void {+ if (!(error instanceof ApiError)) {+ lemonToast.error(messages.failed)+ throw error+ }+ // Gateway timeouts (e.g. an empty-bodied 503) usually succeed on retry.+ lemonToast.error(isTransientServerError(error) ? messages.timedOut : error.detail || messages.failed)+ if (error.status === undefined && !(error instanceof NetworkError)) {+ throw error+ }+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface addSavedInsightsModalLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogic@@ -367,7 +399,7 @@ export const addSavedInsightsModalLogic = kea<addSavedInsightsModalLogicType>([try {actions.setDashboardUpdateLoading(insight.id, true)const response = await insightsApi.update(insight.id, {- dashboards: [...(insight.dashboards || []), dashboardId],+ dashboards: [...currentDashboardIds(insight), dashboardId],})if (response) {actions.updateInsight(response)@@ -378,15 +410,10 @@ export const addSavedInsightsModalLogic = kea<addSavedInsightsModalLogicType>([}} catch (e) {actions.dashboardUpdateFailed(insight.id)- if (isTransientServerError(e)) {- // Gateway timeouts (e.g. an empty-bodied 503) usually succeed on retry. We've handled- // the failure, so stop here rather than rethrowing into error tracking as an unhandled- // rejection.- lemonToast.error('Adding the insight to the dashboard timed out. Try again in a moment.')- return- }- lemonToast.error('Failed to add insight to dashboard')- throw e+ handleDashboardUpdateFailure(e, {+ timedOut: 'Adding the insight to the dashboard timed out. Try again in a moment.',+ failed: 'Failed to add insight to dashboard',+ })} finally {eventUsageLogic.actions.reportSavedInsightToDashboard(insight, dashboardId)actions.setDashboardUpdateLoading(insight.id, false)@@ -396,8 +423,7 @@ export const addSavedInsightsModalLogic = kea<addSavedInsightsModalLogicType>([try {actions.setDashboardUpdateLoading(insight.id, true)const response = await insightsApi.update(insight.id, {- dashboards: (insight.dashboards || []).filter((d) => d !== dashboardId),- dashboard_tiles: (insight.dashboard_tiles || []).filter((dt) => dt.dashboard_id !== dashboardId),+ dashboards: currentDashboardIds(insight).filter((d) => d !== dashboardId),})if (response) {actions.updateInsight(response)@@ -408,15 +434,10 @@ export const addSavedInsightsModalLogic = kea<addSavedInsightsModalLogicType>([}} catch (e) {actions.dashboardUpdateFailed(insight.id)- if (isTransientServerError(e)) {- // Gateway timeouts (e.g. an empty-bodied 503) usually succeed on retry. We've handled- // the failure, so stop here rather than rethrowing into error tracking as an unhandled- // rejection.- lemonToast.error('Removing the insight from the dashboard timed out. Try again in a moment.')- return- }- lemonToast.error('Failed to remove insight from dashboard')- throw e+ handleDashboardUpdateFailure(e, {+ timedOut: 'Removing the insight from the dashboard timed out. Try again in a moment.',+ failed: 'Failed to remove insight from dashboard',+ })} finally {eventUsageLogic.actions.reportRemovedInsightFromDashboard(insight, dashboardId)actions.setDashboardUpdateLoading(insight.id, false)