try-error Documentation
React Components
Pre-built components for common error handling patterns in React applications
TryErrorBoundary
A React Error Boundary specifically designed to work with try-error, providing enhanced error information and recovery options.
TryErrorBoundary Props Interfacetypescript
interface TryErrorBoundaryProps {
fallback: React.ComponentType<{
error: TryError;
resetError: () => void;
retry: () => void;
}>;
onError?: (error: TryError, errorInfo: React.ErrorInfo) => void;
children: React.ReactNode;
}
Example
TryErrorBoundary Usagetsx
1import { TryErrorBoundary } from '@try-error/react';
2
3function ErrorFallback({ error, resetError, retry }) {
4 return (
5 <div className="p-6 bg-red-50 border border-red-200 rounded-lg">
6 <h2 className="text-lg font-semibold text-red-800 mb-2">
7 Something went wrong
8 </h2>
9 <p className="text-red-600 mb-4">{error.message}</p>
10
11 {error.context && (
12 <details className="mb-4">
13 <summary className="cursor-pointer text-red-700">
14 Error Details
15 </summary>
16 <pre className="mt-2 text-sm bg-red-100 p-2 rounded">
17 {JSON.stringify(error.context, null, 2)}
18 </pre>
19 </details>
20 )}
21
22 <div className="flex gap-2">
23 <button
24 onClick={retry}
25 className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
26 >
27 Try Again
28 </button>
29 <button
30 onClick={resetError}
31 className="px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700"
32 >
33 Reset
34 </button>
35 </div>
36 </div>
37 );
38}
39
40function App() {
41 return (
42 <TryErrorBoundary
43 fallback={ErrorFallback}
44 onError={(error, errorInfo) => {
45 console.error('Error caught by boundary:', error);
46 // Send to error reporting service
47 }}
48 >
49 <UserDashboard />
50 </TryErrorBoundary>
51 );
52}
AsyncComponent
A component that handles async operations with built-in loading, error, and success states.
AsyncComponent Props Interfacetypescript
interface AsyncComponentProps<T> {
asyncFn: () => Promise<T>;
deps?: React.DependencyList;
loadingComponent?: React.ComponentType;
errorComponent?: React.ComponentType<{ error: TryError; retry: () => void }>;
children: (data: T) => React.ReactNode;
}
Example
AsyncComponent Usagetsx
1import { AsyncComponent } from '@try-error/react';
2
3function UserProfile({ userId }: { userId: string }) {
4 return (
5 <AsyncComponent
6 asyncFn={() => fetchUser(userId)}
7 deps={[userId]}
8 loadingComponent={() => (
9 <div className="animate-pulse">
10 <div className="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
11 <div className="h-4 bg-gray-200 rounded w-1/2"></div>
12 </div>
13 )}
14 errorComponent={({ error, retry }) => (
15 <div className="text-red-600">
16 <p>Failed to load user: {error.message}</p>
17 <button onClick={retry} className="mt-2 px-4 py-2 bg-blue-500 text-white rounded">
18 Retry
19 </button>
20 </div>
21 )}
22 >
23 {(user) => (
24 <div>
25 <h1 className="text-2xl font-bold">{user.name}</h1>
26 <p className="text-gray-600">{user.email}</p>
27 <p className="text-sm text-gray-500">ID: {user.id}</p>
28 </div>
29 )}
30 </AsyncComponent>
31 );
32}
TryForm
A form component that handles submission with try-error, providing automatic loading states and error handling.
TryForm Props Interfacetypescript
interface TryFormProps<T> {
onSubmit: (data: FormData) => Promise<T>;
onSuccess?: (result: T) => void;
onError?: (error: TryError) => void;
children: (state: {
loading: boolean;
error: TryError | null;
submit: (e: React.FormEvent) => void;
}) => React.ReactNode;
}
Example
TryForm Usagetsx
1import { TryForm } from '@try-error/react';
2
3function CreateUserForm() {
4 return (
5 <TryForm
6 onSubmit={async (formData) => {
7 const response = await fetch('/api/users', {
8 method: 'POST',
9 body: formData,
10 });
11 if (!response.ok) throw new Error('Failed to create user');
12 return response.json();
13 }}
14 onSuccess={(user) => {
15 alert(`User ${user.name} created successfully!`);
16 }}
17 >
18 {({ loading, error, submit }) => (
19 <form onSubmit={submit} className="space-y-4">
20 <div>
21 <label htmlFor="name" className="block text-sm font-medium">
22 Name
23 </label>
24 <input
25 id="name"
26 name="name"
27 type="text"
28 required
29 className="mt-1 block w-full rounded-md border-gray-300 shadow-sm"
30 />
31 </div>
32
33 <div>
34 <label htmlFor="email" className="block text-sm font-medium">
35 Email
36 </label>
37 <input
38 id="email"
39 name="email"
40 type="email"
41 required
42 className="mt-1 block w-full rounded-md border-gray-300 shadow-sm"
43 />
44 </div>
45
46 {error && (
47 <div className="text-red-600 text-sm">
48 Error: {error.message}
49 </div>
50 )}
51
52 <button
53 type="submit"
54 disabled={loading}
55 className="w-full py-2 px-4 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
56 >
57 {loading ? 'Creating...' : 'Create User'}
58 </button>
59 </form>
60 )}
61 </TryForm>
62 );
63}
RetryButton
A button component that handles retry logic with exponential backoff and loading states.
RetryButton Props Interfacetypescript
interface RetryButtonProps {
onRetry: () => Promise<void>;
maxRetries?: number;
backoffMs?: number;
children?: React.ReactNode;
className?: string;
}
Example
RetryButton Usagetsx
1import { RetryButton } from '@try-error/react';
2
3function DataFetcher() {
4 const [data, setData] = useState(null);
5 const [error, setError] = useState(null);
6
7 const fetchData = async () => {
8 const result = await tryAsync(() => fetch('/api/data'));
9 if (isTryError(result)) {
10 setError(result);
11 throw result; // RetryButton will catch this
12 }
13 setData(result);
14 setError(null);
15 };
16
17 if (error) {
18 return (
19 <div className="text-center">
20 <p className="text-red-600 mb-4">Failed to load data: {error.message}</p>
21 <RetryButton
22 onRetry={fetchData}
23 maxRetries={3}
24 backoffMs={1000}
25 className="px-4 py-2 bg-blue-500 text-white rounded"
26 >
27 Retry Loading Data
28 </RetryButton>
29 </div>
30 );
31 }
32
33 return data ? <DataDisplay data={data} /> : <LoadingSpinner />;
34}
ErrorDisplay
A component for displaying TryError objects with rich formatting and debugging information.
ErrorDisplay Props Interfacetypescript
interface ErrorDisplayProps {
error: TryError;
showStack?: boolean;
showContext?: boolean;
showTimestamp?: boolean;
onDismiss?: () => void;
className?: string;
}
Example
ErrorDisplay Usagetsx
1import { ErrorDisplay } from '@try-error/react';
2
3function UserProfile({ userId }: { userId: string }) {
4 const { data: user, error } = useTryAsync(
5 () => fetchUser(userId),
6 [userId]
7 );
8
9 if (error) {
10 return (
11 <ErrorDisplay
12 error={error}
13 showContext={process.env.NODE_ENV === 'development'}
14 showStack={process.env.NODE_ENV === 'development'}
15 showTimestamp
16 onDismiss={() => window.location.reload()}
17 className="max-w-md mx-auto"
18 />
19 );
20 }
21
22 return user ? <UserDetails user={user} /> : <LoadingSpinner />;
23}
Best Practices
✅ Do
- • Use TryErrorBoundary at the top level of your app
- • Provide meaningful fallback UIs for error states
- • Include retry mechanisms where appropriate
- • Show different error details in development vs production
- • Use loading states to improve user experience
❌ Don't
- • Ignore error states in your components
- • Show technical error details to end users
- • Forget to provide retry mechanisms for transient errors
- • Use generic error messages without context