Add default ErrorBoundary with iframe postMessage to template.

This commit is contained in:
Chad Curtis 2025-07-17 17:18:58 +00:00
parent c5dabfdb3a
commit d17fc5ddd7
3 changed files with 239 additions and 1 deletions

View File

@ -0,0 +1,143 @@
import { Component, ErrorInfo, ReactNode } from 'react';
interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
errorInfo: ErrorInfo | null;
}
interface ErrorBoundaryProps {
children: ReactNode;
fallback?: ReactNode;
}
interface ErrorMessage {
type: 'mkstack-error';
error: {
message: string;
stack?: string;
componentStack?: string;
url: string;
timestamp: string;
userAgent: string;
};
}
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: null,
};
}
static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {
return {
hasError: true,
error,
};
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('Error caught by ErrorBoundary:', error, errorInfo);
// Send error details via postMessage for iframe embedding
const errorMessage: ErrorMessage = {
type: 'mkstack-error',
error: {
message: error.message,
stack: error.stack || undefined,
componentStack: errorInfo.componentStack || undefined,
url: window.location.href,
timestamp: new Date().toISOString(),
userAgent: navigator.userAgent,
},
};
// Send to parent window if in iframe, or broadcast to all
if (window.parent !== window) {
window.parent.postMessage(errorMessage, '*');
} else {
window.postMessage(errorMessage, '*');
}
this.setState({
error,
errorInfo,
});
}
handleReset = () => {
this.setState({
hasError: false,
error: null,
errorInfo: null,
});
};
render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
return (
<div className="min-h-screen bg-background flex items-center justify-center p-4">
<div className="max-w-md w-full space-y-4">
<div className="text-center">
<h2 className="text-2xl font-bold text-foreground mb-2">
Something went wrong
</h2>
<p className="text-muted-foreground">
An unexpected error occurred. The error has been reported.
</p>
</div>
<div className="bg-muted p-4 rounded-lg">
<details className="text-sm">
<summary className="cursor-pointer font-medium text-foreground">
Error details
</summary>
<div className="mt-2 space-y-2">
<div>
<strong className="text-foreground">Message:</strong>
<p className="text-muted-foreground mt-1">
{this.state.error?.message}
</p>
</div>
{this.state.error?.stack && (
<div>
<strong className="text-foreground">Stack trace:</strong>
<pre className="text-xs text-muted-foreground mt-1 overflow-auto max-h-32">
{this.state.error.stack}
</pre>
</div>
)}
</div>
</details>
</div>
<div className="flex gap-2">
<button
onClick={this.handleReset}
className="flex-1 px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors"
>
Try again
</button>
<button
onClick={() => window.location.reload()}
className="flex-1 px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90 transition-colors"
>
Reload page
</button>
</div>
</div>
</div>
);
}
return this.props.children;
}
}

View File

@ -3,10 +3,15 @@ import { createRoot } from 'react-dom/client';
// Import polyfills first
import './lib/polyfills.ts';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import App from './App.tsx';
import './index.css';
// FIXME: a custom font should be used. Eg:
// import '@fontsource-variable/<font-name>';
createRoot(document.getElementById("root")!).render(<App />);
createRoot(document.getElementById("root")!).render(
<ErrorBoundary>
<App />
</ErrorBoundary>
);

View File

@ -0,0 +1,90 @@
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { ErrorBoundary } from '@/components/ErrorBoundary';
// Mock window.postMessage
const postMessageMock = vi.fn();
Object.defineProperty(window, 'postMessage', {
value: postMessageMock,
});
// Test component that throws an error
const ThrowError = ({ shouldThrow }: { shouldThrow: boolean }) => {
if (shouldThrow) {
throw new Error('Test error');
}
return <div>No error</div>;
};
describe('ErrorBoundary', () => {
it('renders children when no error occurs', () => {
render(
<ErrorBoundary>
<div>Test content</div>
</ErrorBoundary>
);
expect(screen.getByText('Test content')).toBeInTheDocument();
});
it('catches and displays error when child throws', () => {
// Suppress console.error for this test
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
render(
<ErrorBoundary>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
expect(screen.getByText('An unexpected error occurred. The error has been reported.')).toBeInTheDocument();
consoleSpy.mockRestore();
});
it('sends error details via postMessage', () => {
// Suppress console.error for this test
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
postMessageMock.mockClear();
render(
<ErrorBoundary>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
expect(postMessageMock).toHaveBeenCalledWith(
expect.objectContaining({
type: 'mkstack-error',
error: expect.objectContaining({
message: 'Test error',
stack: expect.any(String),
url: expect.any(String),
timestamp: expect.any(String),
userAgent: expect.any(String),
}),
}),
'*'
);
consoleSpy.mockRestore();
});
it('uses custom fallback when provided', () => {
const customFallback = <div>Custom error message</div>;
// Suppress console.error for this test
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
render(
<ErrorBoundary fallback={customFallback}>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
expect(screen.getByText('Custom error message')).toBeInTheDocument();
consoleSpy.mockRestore();
});
});