Implement robust error handling in Google Antigravity React applications with error boundaries, fallback UIs, and error reporting.
# Error Boundary Implementation Guide
Build resilient Google Antigravity applications with comprehensive error boundary implementations. This guide covers error catching, fallback UIs, error reporting, and recovery patterns.
## Error Boundary Component
Create a reusable error boundary with recovery capabilities:
```typescript
// components/ErrorBoundary.tsx
"use client";
import { Component, ErrorInfo, ReactNode } from "react";
interface ErrorBoundaryProps {
children: ReactNode;
fallback?: ReactNode;
onError?: (error: Error, errorInfo: ErrorInfo) => void;
resetKeys?: unknown[];
}
interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
errorInfo: ErrorInfo | null;
}
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): void {
this.setState({ errorInfo });
// Report to error tracking service
this.props.onError?.(error, errorInfo);
// Log to console in development
if (process.env.NODE_ENV === "development") {
console.error("Error caught by boundary:", error);
console.error("Component stack:", errorInfo.componentStack);
}
}
componentDidUpdate(prevProps: ErrorBoundaryProps): void {
// Reset error state when resetKeys change
if (
this.state.hasError &&
this.props.resetKeys &&
prevProps.resetKeys &&
!this.areResetKeysEqual(prevProps.resetKeys, this.props.resetKeys)
) {
this.setState({
hasError: false,
error: null,
errorInfo: null,
});
}
}
private areResetKeysEqual(prev: unknown[], next: unknown[]): boolean {
return (
prev.length === next.length &&
prev.every((key, index) => Object.is(key, next[index]))
);
}
private handleReset = (): void => {
this.setState({
hasError: false,
error: null,
errorInfo: null,
});
};
render(): ReactNode {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
return (
<ErrorFallback
error={this.state.error}
resetError={this.handleReset}
/>
);
}
return this.props.children;
}
}
```
## Error Fallback UI
Create user-friendly error fallback components:
```typescript
// components/ErrorFallback.tsx
"use client";
import { useRouter } from "next/navigation";
interface ErrorFallbackProps {
error: Error | null;
resetError: () => void;
}
export function ErrorFallback({ error, resetError }: ErrorFallbackProps) {
const router = useRouter();
return (
<div className="min-h-[400px] flex items-center justify-center p-8">
<div className="text-center max-w-md">
<div className="text-6xl mb-4">⚠️</div>
<h2 className="text-2xl font-bold mb-2">Something went wrong</h2>
<p className="text-gray-600 mb-6">
{error?.message || "An unexpected error occurred"}
</p>
<div className="flex gap-4 justify-center">
<button
onClick={resetError}
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
>
Try Again
</button>
<button
onClick={() => router.push("/")}
className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
>
Go Home
</button>
</div>
{process.env.NODE_ENV === "development" && error && (
<details className="mt-6 text-left">
<summary className="cursor-pointer text-sm text-gray-500">
Error Details
</summary>
<pre className="mt-2 p-4 bg-gray-100 rounded text-xs overflow-auto">
{error.stack}
</pre>
</details>
)}
</div>
</div>
);
}
```
## Error Reporting Integration
Integrate with error tracking services:
```typescript
// lib/error-reporting.ts
import { ErrorInfo } from "react";
interface ErrorReport {
message: string;
stack?: string;
componentStack?: string;
url: string;
timestamp: string;
userAgent: string;
userId?: string;
}
export async function reportError(
error: Error,
errorInfo?: ErrorInfo
): Promise<void> {
const report: ErrorReport = {
message: error.message,
stack: error.stack,
componentStack: errorInfo?.componentStack,
url: typeof window !== "undefined" ? window.location.href : "",
timestamp: new Date().toISOString(),
userAgent: typeof navigator !== "undefined" ? navigator.userAgent : "",
};
// Send to your error tracking endpoint
try {
await fetch("/api/errors", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(report),
});
} catch (e) {
console.error("Failed to report error:", e);
}
}
```
## Usage in Application
Wrap components strategically:
```typescript
// app/layout.tsx
import { ErrorBoundary } from "@/components/ErrorBoundary";
import { reportError } from "@/lib/error-reporting";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<ErrorBoundary onError={reportError}>
<Header />
<main>{children}</main>
<Footer />
</ErrorBoundary>
</body>
</html>
);
}
```
## Best Practices
1. **Granular Boundaries**: Place error boundaries at logical component boundaries
2. **Graceful Degradation**: Show partial UI when possible instead of full error
3. **Error Logging**: Always report errors to monitoring services
4. **Recovery Actions**: Provide clear actions users can take to recover
5. **Development Details**: Show stack traces only in development
6. **Reset Mechanisms**: Allow users to retry after transient errorsThis react prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their react implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For react projects, consider mentioning your framework version, coding style, and any specific libraries you're using.