Comprehensive error handling with error boundaries, suspense, and graceful degradation
# React Error Handling Patterns for Google Antigravity
Build resilient React applications with Google Antigravity's Gemini 3 engine. This guide covers error boundaries, suspense error handling, async error patterns, and graceful degradation.
## Error Boundary Component
```typescript
// components/ErrorBoundary.tsx
'use client';
import { Component, ReactNode } from 'react';
interface Props {
children: ReactNode;
fallback?: ReactNode;
onError?: (error: Error, errorInfo: React.ErrorInfo) => void;
}
interface State {
hasError: boolean;
error: Error | null;
}
export class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
console.error('Error caught by boundary:', error, errorInfo);
this.props.onError?.(error, errorInfo);
// Report to error tracking service
reportError(error, errorInfo);
}
render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
return (
<div className="p-6 bg-red-50 border border-red-200 rounded-lg">
<h2 className="text-lg font-semibold text-red-800">
Something went wrong
</h2>
<p className="mt-2 text-red-600">
{this.state.error?.message || 'An unexpected error occurred'}
</p>
<button
onClick={() => this.setState({ hasError: false, error: null })}
className="mt-4 px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
>
Try again
</button>
</div>
);
}
return this.props.children;
}
}
// Functional wrapper for hooks support
export function withErrorBoundary<P extends object>(
Component: React.ComponentType<P>,
fallback?: ReactNode
) {
return function WithErrorBoundary(props: P) {
return (
<ErrorBoundary fallback={fallback}>
<Component {...props} />
</ErrorBoundary>
);
};
}
```
## Next.js Error Files
```typescript
// app/error.tsx
'use client';
import { useEffect } from 'react';
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
// Log error to monitoring service
console.error('Page error:', error);
}, [error]);
return (
<div className="min-h-[400px] flex items-center justify-center">
<div className="text-center">
<h2 className="text-2xl font-bold text-gray-900 mb-4">
Something went wrong!
</h2>
<p className="text-gray-600 mb-6">
We encountered an error while loading this page.
</p>
<div className="space-x-4">
<button
onClick={reset}
className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
>
Try again
</button>
<a
href="/"
className="px-6 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
>
Go home
</a>
</div>
{process.env.NODE_ENV === 'development' && (
<pre className="mt-8 p-4 bg-gray-100 rounded text-left text-sm overflow-auto">
{error.message}
{error.stack}
</pre>
)}
</div>
</div>
);
}
// app/global-error.tsx - Root layout errors
'use client';
export default function GlobalError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
return (
<html>
<body>
<div className="min-h-screen flex items-center justify-center bg-gray-100">
<div className="bg-white p-8 rounded-lg shadow-lg text-center">
<h2 className="text-2xl font-bold mb-4">Application Error</h2>
<p className="text-gray-600 mb-6">
A critical error occurred. Please try refreshing the page.
</p>
<button
onClick={reset}
className="px-6 py-2 bg-blue-600 text-white rounded-lg"
>
Refresh
</button>
</div>
</div>
</body>
</html>
);
}
```
## Async Error Handling Hook
```typescript
// hooks/useAsyncError.ts
import { useState, useCallback } from 'react';
interface AsyncState<T> {
data: T | null;
error: Error | null;
isLoading: boolean;
}
export function useAsync<T>(asyncFn: () => Promise<T>) {
const [state, setState] = useState<AsyncState<T>>({
data: null,
error: null,
isLoading: false,
});
const execute = useCallback(async () => {
setState({ data: null, error: null, isLoading: true });
try {
const data = await asyncFn();
setState({ data, error: null, isLoading: false });
return data;
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
setState({ data: null, error: err, isLoading: false });
throw err;
}
}, [asyncFn]);
const reset = useCallback(() => {
setState({ data: null, error: null, isLoading: false });
}, []);
return { ...state, execute, reset };
}
// Usage
function UserProfile({ userId }: { userId: string }) {
const { data: user, error, isLoading, execute } = useAsync(
() => fetchUser(userId)
);
useEffect(() => {
execute();
}, [execute]);
if (isLoading) return <Spinner />;
if (error) return <ErrorMessage error={error} onRetry={execute} />;
if (!user) return null;
return <Profile user={user} />;
}
```
## Query Error Handling
```typescript
// hooks/useQueryWithError.ts
import { useQuery, UseQueryOptions } from '@tanstack/react-query';
import { toast } from 'sonner';
export function useQueryWithErrorHandling<T>(
key: string[],
queryFn: () => Promise<T>,
options?: Omit<UseQueryOptions<T, Error>, 'queryKey' | 'queryFn'>
) {
return useQuery({
queryKey: key,
queryFn,
...options,
meta: {
...options?.meta,
onError: (error: Error) => {
// Show toast notification
toast.error(error.message || 'An error occurred');
// Call custom error handler if provided
options?.meta?.onError?.(error);
},
},
});
}
// Global error handler in QueryClient
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: (failureCount, error: any) => {
// Don't retry on 4xx errors
if (error?.status >= 400 && error?.status < 500) {
return false;
}
return failureCount < 3;
},
},
mutations: {
onError: (error: Error) => {
toast.error(error.message || 'Operation failed');
},
},
},
});
```
## Form Error Handling
```typescript
// components/forms/FormWithErrors.tsx
'use client';
import { useFormState } from 'react-dom';
import { submitForm } from '@/app/actions';
interface FormState {
success: boolean;
errors?: {
fieldErrors?: Record<string, string[]>;
formError?: string;
};
}
const initialState: FormState = { success: false };
export function ContactForm() {
const [state, formAction] = useFormState(submitForm, initialState);
return (
<form action={formAction} className="space-y-4">
{state.errors?.formError && (
<div className="p-4 bg-red-50 border border-red-200 rounded-lg">
<p className="text-red-600">{state.errors.formError}</p>
</div>
)}
<div>
<label htmlFor="email" className="block text-sm font-medium">
Email
</label>
<input
type="email"
id="email"
name="email"
className={`mt-1 block w-full rounded-md border px-3 py-2 ${
state.errors?.fieldErrors?.email ? 'border-red-500' : 'border-gray-300'
}`}
/>
{state.errors?.fieldErrors?.email && (
<p className="mt-1 text-sm text-red-600">
{state.errors.fieldErrors.email[0]}
</p>
)}
</div>
<SubmitButton />
</form>
);
}
```
## Best Practices
Google Antigravity's Gemini 3 engine recommends these error handling patterns: Implement error boundaries at strategic UI levels. Provide user-friendly error messages with recovery options. Log errors to monitoring services for debugging. Use typed error classes for better error categorization. Implement graceful degradation for non-critical failures.This 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.