: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(frontend): handle thrown null and undefined in app error boundaries (#129790)
Rafael Audiberteefdabee8633
diff --git a/frontend/src/RootErrorBoundary.test.tsx b/frontend/src/RootErrorBoundary.test.tsxindex 7ba43713c839..1714553e4ef8 100644--- a/frontend/src/RootErrorBoundary.test.tsx+++ b/frontend/src/RootErrorBoundary.test.tsx@@ -8,6 +8,10 @@ function ThrowRenderError(): JSX.Element {throw new Error('boot render kaboom')}+function ThrowNull(): JSX.Element {+ throw null+}+function ThrowChunkError(): JSX.Element {throw new TypeError('Failed to fetch dynamically imported module: /static/chunk-App.js')}@@ -65,6 +69,17 @@ describe('RootErrorBoundary', () => {expect(event.properties.chunk_load_error).toBe(false)})+ it('shows crash copy when a component throws null', () => {+ render(+ <RootErrorBoundary>+ <ThrowNull />+ </RootErrorBoundary>+ )++ expect(screen.getByRole('alert')).toHaveTextContent('PostHog crashed while starting.')+ expect(JSON.parse(sendBeacon.mock.calls[0][1]).properties.$exception_list[0].value).toBe('null')+ })+it('shows load-failure copy for chunk-load errors', () => {render(<RootErrorBoundary>diff --git a/frontend/src/RootErrorBoundary.tsx b/frontend/src/RootErrorBoundary.tsxindex 8a95bf2d68cc..989a09de932c 100644--- a/frontend/src/RootErrorBoundary.tsx+++ b/frontend/src/RootErrorBoundary.tsx@@ -55,6 +55,7 @@ function reportBootFailure(error: unknown): void {}interface RootErrorBoundaryState {+ hasError: booleanerror: unknown}@@ -66,10 +67,10 @@ interface RootErrorBoundaryState {* (see index.tsx); only errors that survive that recovery surface here.*/export class RootErrorBoundary extends React.Component<{ children: React.ReactNode }, RootErrorBoundaryState> {- override state: RootErrorBoundaryState = { error: null }+ override state: RootErrorBoundaryState = { hasError: false, error: null }static getDerivedStateFromError(error: unknown): RootErrorBoundaryState {- return { error }+ return { hasError: true, error }}override componentDidCatch(error: unknown, errorInfo: React.ErrorInfo): void {@@ -78,7 +79,7 @@ export class RootErrorBoundary extends React.Component<{ children: React.ReactNo}override render(): React.ReactNode {- if (this.state.error) {+ if (this.state.hasError) {return (<div className="Preloader" role="alert"><div>diff --git a/frontend/src/layout/ErrorBoundary/ErrorBoundary.test.tsx b/frontend/src/layout/ErrorBoundary/ErrorBoundary.test.tsxindex b44660e96eee..47e9de7ce451 100644--- a/frontend/src/layout/ErrorBoundary/ErrorBoundary.test.tsx+++ b/frontend/src/layout/ErrorBoundary/ErrorBoundary.test.tsx@@ -3,6 +3,7 @@ import '@testing-library/jest-dom'import { cleanup, render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { Provider } from 'kea'+import posthog from 'posthog-js'import { initKeaTests } from '~/test/init'@@ -14,6 +15,7 @@ const REMOVE_CHILD_MESSAGE =let renderAttempts = 0let throwUntilAttempt = 0let thrownMessage = REMOVE_CHILD_MESSAGE+let thrownValue: unknown = undefined/*** Throws on every render attempt up to `throwUntilAttempt`. React retries a failed render twice@@ -22,7 +24,7 @@ let thrownMessage = REMOVE_CHILD_MESSAGEfunction Unstable(): JSX.Element {renderAttempts += 1if (renderAttempts <= throwUntilAttempt) {- throw new Error(thrownMessage)+ throw thrownValue !== undefined ? thrownValue : new Error(thrownMessage)}return <div>recovered content</div>}@@ -35,6 +37,7 @@ describe('ErrorBoundary', () => {renderAttempts = 0throwUntilAttempt = 0thrownMessage = REMOVE_CHILD_MESSAGE+ thrownValue = undefinedconsoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})})@@ -43,10 +46,10 @@ describe('ErrorBoundary', () => {consoleErrorSpy.mockRestore()})- function renderBoundary(): void {+ function renderBoundary(exceptionProps?: Record<string, string>): void {render(<Provider>- <ErrorBoundary>+ <ErrorBoundary exceptionProps={exceptionProps}><Unstable /></ErrorBoundary></Provider>@@ -82,6 +85,25 @@ describe('ErrorBoundary', () => {expect(screen.queryByText(/translation/i)).not.toBeInTheDocument()})+ it.each([+ { value: null, described: 'null' },+ { value: 'oops', described: 'string oops' },+ ])('names the scene and records a thrown $value', ({ value, described }) => {+ const captureSpy = jest.spyOn(posthog, 'captureException')+ thrownValue = value+ throwUntilAttempt = 3+ renderBoundary({ feature: 'Insight' })++ expect(+ screen.getByText(`Non-Error value thrown in scene Insight: ${described}`, { exact: false })+ ).toBeInTheDocument()+ expect(captureSpy).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ feature: 'Insight', thrown_value: described })+ )+ captureSpy.mockRestore()+ })+// The app-root boundary in scenes/App.tsx has no key to remount it, so without an in-fallback// reset a crash outside a scene (nav, command palette) can only be cleared by a reload.it('re-renders its children when the user clicks Try again', async () => {diff --git a/frontend/src/layout/ErrorBoundary/ErrorBoundary.tsx b/frontend/src/layout/ErrorBoundary/ErrorBoundary.tsxindex cdd193d58046..ce892b569149 100644--- a/frontend/src/layout/ErrorBoundary/ErrorBoundary.tsx+++ b/frontend/src/layout/ErrorBoundary/ErrorBoundary.tsx@@ -54,6 +54,40 @@ function RemountOnMount({ onRemount }: { onRemount: () => void }): null {return null}+const MAX_THROWN_VALUE_LENGTH = 200++function isErrorLike(value: unknown): value is Error {+ return value instanceof Error || Object.prototype.toString.call(value) === '[object Error]'+}++function describeThrownValue(value: unknown): string {+ if (value === null || value === undefined) {+ return String(value)+ }+ let text: string+ try {+ text = String(value)+ } catch {+ text = '<unprintable>'+ }+ return `${typeof value} ${text.slice(0, MAX_THROWN_VALUE_LENGTH)}`+}++type ExceptionProperties = Record<string, number | string | boolean | bigint | symbol | null | undefined>++/** A property, because rethrowing an Error from an inner boundary would replace React's component stack. */+function withThrownValue(properties: ExceptionProperties): (error: unknown) => ExceptionProperties {+ return (error) => (isErrorLike(error) ? properties : { ...properties, thrown_value: describeThrownValue(error) })+}++function toDisplayError(error: unknown, scene: unknown): Error {+ if (isErrorLike(error)) {+ return error+ }+ const location = typeof scene === 'string' && scene ? ` in scene ${scene}` : ''+ return new Error(`Non-Error value thrown${location}: ${describeThrownValue(error)}`)+}+interface RemountRecord {count: numberat: number@@ -65,7 +99,7 @@ function canRemountSilently(record: RemountRecord, now: number): boolean {interface ErrorBoundaryProps {children?: React.ReactNode- exceptionProps?: Record<string, number | string | boolean | bigint | symbol | null | undefined>+ exceptionProps?: ExceptionPropertiesclassName?: string}@@ -106,13 +140,9 @@ export function ErrorBoundary({ children, exceptionProps = {}, className }: Erroreturn (<PostHogErrorBoundarykey={remountCount}- additionalProperties={additionalProperties}+ additionalProperties={withThrownValue(additionalProperties)}fallback={(props: PostHogErrorBoundaryFallbackProps) => {- const rawError = props.error- const normalizedError =- rawError instanceof Error- ? rawError- : new Error(typeof rawError === 'string' ? rawError : 'Unknown error')+ const normalizedError = toDisplayError(props.error, exceptionProps.feature)const { stack, name, message } = normalizedErrorconst exceptionEvent = props.exceptionEvent as SupportTicketExceptionEvent@@ -212,13 +242,9 @@ export function LightErrorBoundary({ children, exceptionProps = {}, className }:}return (<PostHogErrorBoundary- additionalProperties={additionalProperties}+ additionalProperties={withThrownValue(additionalProperties)}fallback={(props: PostHogErrorBoundaryFallbackProps) => {- const rawError = props.error- const normalizedError =- rawError instanceof Error- ? rawError- : new Error(typeof rawError === 'string' ? rawError : 'Unknown error')+ const normalizedError = toDisplayError(props.error, exceptionProps.feature)const { stack, name, message } = normalizedErrorreturn (<div className={clsx('text-danger', className)}>diff --git a/frontend/src/scenes/ChunkLoadErrorBoundary.tsx b/frontend/src/scenes/ChunkLoadErrorBoundary.tsxindex 058847ebf523..6c8dbf5da221 100644--- a/frontend/src/scenes/ChunkLoadErrorBoundary.tsx+++ b/frontend/src/scenes/ChunkLoadErrorBoundary.tsx@@ -7,6 +7,7 @@ const RELOAD_GUARD_KEY = 'posthog-chunk-reload-at'const RELOAD_GUARD_WINDOW_MS = 20_000interface State {+ hasError: booleanerror: unknownsurface: boolean}@@ -26,10 +27,10 @@ interface ChunkLoadErrorBoundaryProps {}export class ChunkLoadErrorBoundary extends Component<ChunkLoadErrorBoundaryProps, State> {- override state: State = { error: null, surface: false }+ override state: State = { hasError: false, error: null, surface: false }static getDerivedStateFromError(error: unknown): Partial<State> {- return { error }+ return { hasError: true, error }}override componentDidCatch(error: unknown): void {@@ -63,16 +64,16 @@ export class ChunkLoadErrorBoundary extends Component<ChunkLoadErrorBoundaryProp}override render(): ReactNode {- const { error, surface } = this.state- if (error && surface && isChunkLoadError(error) && this.props.fallback) {+ const { hasError, error, surface } = this.state+ if (!hasError) {+ return this.props.children+ }+ if (surface && isChunkLoadError(error) && this.props.fallback) {return this.props.fallback(error)}- if (error && (!isChunkLoadError(error) || surface)) {+ if (!isChunkLoadError(error) || surface) {throw error}- if (error && isChunkLoadError(error)) {- return null- }- return this.props.children+ return null}}