: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(data-warehouse): surface errors when creating a DAG from a view (#66979)
Thiago Salvatore61ebd93b5211
diff --git a/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.test.tsx b/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.test.tsxnew file mode 100644index 000000000000..5b9c65f68d04--- /dev/null+++ b/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.test.tsx@@ -0,0 +1,99 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen, waitFor, waitForElementToBeRemoved } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import posthog from 'posthog-js'++import { ApiError } from 'lib/api-error'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'++import { initKeaTests } from '~/test/init'++import { LemonFormDialog } from './LemonDialog'++describe('LemonFormDialog', () => {+ let captureException: jest.SpyInstance++ beforeEach(() => {+ initKeaTests()+ // react-modal needs an app element to hide from screen readers on open.+ document.body.innerHTML = '<div id="root"></div>'+ captureException = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined as any)+ })++ afterEach(() => {+ cleanup()+ jest.restoreAllMocks()+ })++ function renderDialog(onSubmit: (values: Record<string, any>) => void | Promise<void>): void {+ render(+ <LemonFormDialog+ dialogKey="test-dialog"+ title="Test dialog"+ shouldAwaitSubmit+ initialValues={{ name: 'a name' }}+ content={+ <LemonField name="name">+ <LemonInput />+ </LemonField>+ }+ onSubmit={onSubmit}+ />+ )+ }++ const submitViaButton = async (): Promise<void> => {+ await userEvent.click(screen.getByRole('button', { name: 'Submit' }))+ }++ const submitViaEnter = async (): Promise<void> => {+ screen.getByRole('textbox').focus()+ await userEvent.keyboard('{Enter}')+ }++ it.each([+ ['button click', submitViaButton],+ ['enter key', submitViaEnter],+ ])('keeps the dialog open when the submit rejects (%s)', async (_mode, submit) => {+ const onSubmit = jest.fn().mockRejectedValue(new Error('rejected'))++ renderDialog(onSubmit)+ await submit()++ await waitFor(() => expect(onSubmit).toHaveBeenCalled())+ // Dialog stays open so the user can correct and retry.+ expect(screen.getByRole('button', { name: 'Submit' })).toBeInTheDocument()+ })++ it.each([+ ['unexpected Error', new Error('boom'), true],+ ['5xx ApiError', new ApiError('server error', 500), true],+ ['4xx validation ApiError', new ApiError('reserved name', 400), false],+ ])('only captures unexpected failures, not user-validation errors (%s)', async (_desc, error, shouldCapture) => {+ const onSubmit = jest.fn().mockRejectedValue(error)++ renderDialog(onSubmit)+ await submitViaButton()++ await waitFor(() => expect(onSubmit).toHaveBeenCalled())+ expect(screen.getByRole('button', { name: 'Submit' })).toBeInTheDocument()+ if (shouldCapture) {+ expect(captureException).toHaveBeenCalledWith(error)+ } else {+ expect(captureException).not.toHaveBeenCalled()+ }+ })++ it('closes the dialog and does not capture when the submit resolves', async () => {+ const onSubmit = jest.fn().mockResolvedValue(undefined)++ renderDialog(onSubmit)+ await submitViaButton()++ await waitForElementToBeRemoved(() => screen.queryByRole('button', { name: 'Submit' }))+ expect(onSubmit).toHaveBeenCalled()+ expect(captureException).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.tsx b/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.tsxindex 89ac7989ebc0..434256e88a46 100644--- a/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.tsx+++ b/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.tsx@@ -1,15 +1,26 @@import { useActions, useValues } from 'kea'import { Form } from 'kea-forms'import { router } from 'kea-router'+import posthog from 'posthog-js'import { ReactNode, forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'import { Root, createRoot } from 'react-dom/client'+import { ApiError } from 'lib/api-error'import { LemonButton, LemonButtonProps } from 'lib/lemon-ui/LemonButton'import { LemonModal, LemonModalProps } from 'lib/lemon-ui/LemonModal'import { uuid } from 'lib/utils/dom'import { LemonDialogFormPropsType, lemonDialogLogic } from './lemonDialogLogic'+// A rejected await-submit keeps the dialog open so the user can retry. Capture only genuinely+// unexpected failures — not 4xx validation errors the user is expected to cause (e.g. a reserved+// name), which would otherwise flood the exception tracker on every validation failure.+function captureUnexpectedSubmitError(error: unknown): void {+ if (!(error instanceof ApiError) || (error.status ?? 500) >= 500) {+ posthog.captureException(error)+ }+}+export type LemonFormDialogProps = LemonDialogFormPropsType &Omit<LemonDialogProps, 'primaryButton' | 'secondaryButton' | 'content'> & {initialValues: Record<string, any>@@ -109,6 +120,12 @@ const LemonDialogComponent = forwardRef<LemonDialogRef, LemonDialogProps>(functitry {// eslint-disable-next-line @typescript-eslint/await-thenableawait button.onClick?.(e)+ } catch (error) {+ // The submit handler is responsible for surfacing the error to the user+ // (e.g. via a toast). Keep the dialog open so they can correct and retry,+ // and capture genuine bugs so they aren't silently swallowed.+ captureUnexpectedSubmitError(error)+ return} finally {setIsLoading(false)isLoadingCallback?.(false)@@ -215,7 +232,15 @@ export const LemonFormDialog = ({props.shouldAwaitSubmit? async (e: React.KeyboardEvent<HTMLFormElement>): Promise<void> => {if (e.key === 'Enter' && primaryButton?.htmlType === 'submit' && isFormValid) {- await onSubmit(form)+ try {+ await onSubmit(form)+ } catch (error) {+ // Mirror the button path: keep the dialog open on failure so the+ // user can correct and retry, and capture instead of leaking an+ // unhandled rejection.+ captureUnexpectedSubmitError(error)+ return+ }ref?.current?.closeDialog()}}diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex 25e6d3081cb1..f879920e7d9f 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -1373,11 +1373,21 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([dataModelingLogic.values.dags.map((d) => d.name)),onSubmit: async (dagData) => {- const newDag =- await api.dataModelingDags.create(dagData)- await dataModelingLogic.asyncActions.loadDags()- onSelect(newDag.id)- lemonToast.success('DAG created')+ try {+ const newDag =+ await api.dataModelingDags.create(dagData)+ await dataModelingLogic.asyncActions.loadDags()+ onSelect(newDag.id)+ lemonToast.success('DAG created')+ } catch (error) {+ lemonToast.error(+ error instanceof ApiError+ ? (error.detail ?? 'Failed to create DAG')+ : 'Failed to create DAG'+ )+ // Re-throw so the dialog stays open for the user to retry.+ throw error+ }},})}}diff --git a/products/data_modeling/frontend/DagSelector.tsx b/products/data_modeling/frontend/DagSelector.tsxindex 3a4b1835552c..6f4a054430cf 100644--- a/products/data_modeling/frontend/DagSelector.tsx+++ b/products/data_modeling/frontend/DagSelector.tsx@@ -25,10 +25,15 @@ export function openCreateDagDialog({onSubmit,}: {existingNames: Set<string>- onSubmit: (dag: { name: string; description: string; sync_frequency: DataModelingSyncInterval }) => void+ onSubmit: (dag: {+ name: string+ description: string+ sync_frequency: DataModelingSyncInterval+ }) => void | Promise<void>}): void {LemonDialog.openForm({title: 'New DAG',+ shouldAwaitSubmit: true,initialValues: {dagName: '',dagDescription: '',@@ -61,7 +66,7 @@ export function openCreateDagDialog({},},onSubmit: ({ dagName, dagDescription, syncFrequency }) => {- onSubmit({+ return onSubmit({name: dagName.trim(),description: dagDescription?.trim() ?? '',sync_frequency: syncFrequency,