Lesson 5 of 8
Error Handling Strategies
Error handling has three layers in a production React app: network-level (HTTP errors), component-level (error boundaries for render errors), and UX-level (user-friendly messages with retry). Having a strategy for each layer prevents silent failures.
Error Handling Layers
import { useQueryClient } from '@tanstack/react-query';
import { ErrorBoundary } from 'react-error-boundary';
import toast from 'react-hot-toast';
// Layer 1: Network errors - in Axios interceptor (Module 6 Topic 1)
// Layer 2: TanStack Query - automatic retry, error state
const { data, isError, error, refetch } = useQuery({
queryKey: ['users'],
queryFn: fetchUsers,
retry: 3, // retry up to 3 times before error state
retryDelay: attempt => Math.min(1000 * 2 ** attempt, 30_000), // exponential backoff
});
if (isError) {
return (
<ErrorDisplay
message={error instanceof Error ? error.message : 'Unknown error'}
onRetry={refetch}
/>
);
}
// Layer 3: Error Boundaries - catch render errors
function AppRoot() {
return (
<ErrorBoundary
FallbackComponent={({ error, resetErrorBoundary }) => (
<div style={{ padding: 40, textAlign: 'center' }}>
<h2>Something went wrong</h2>
<pre style={{ color: 'red', fontSize: 12 }}>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try Again</button>
</div>
)}
onError={(error, info) => {
// Log to Sentry/Datadog
logErrorToService(error, info.componentStack);
}}
>
<App />
</ErrorBoundary>
);
}
// Layer 4: User feedback - toast notifications
function useApiMutation<T, Args extends unknown[]>(fn: (...args: Args) => Promise<T>) {
return useMutation({
mutationFn: fn,
onSuccess: () => toast.success('Saved successfully'),
onError: (err: Error) => toast.error(err.message ?? 'Something went wrong'),
});
}
// Centralized error message mapping
const ERROR_MESSAGES: Record<number, string> = {
400: 'Invalid request. Please check your input.',
401: 'You must be signed in to do this.',
403: "You don't have permission to do this.",
404: 'The requested resource was not found.',
422: 'Validation failed. Please check your input.',
429: 'Too many requests. Please slow down.',
500: 'Server error. Please try again later.',
};
function getErrorMessage(err: unknown): string {
if (axios.isAxiosError(err)) {
const status = err.response?.status;
return (status && ERROR_MESSAGES[status]) ?? err.message ?? 'Network error';
}
if (err instanceof Error) return err.message;
return 'An unexpected error occurred';
}Tip
Tip
Practice Error Handling Strategies in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for Error Handling Strategies
Practice Task
Note
Practice Task - (1) Write a working example of Error Handling Strategies from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Error Handling Strategies is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Finished this lesson?