Error Handling Patterns
Reference implementations for toast-based and modal-based error handling in React applications.
Live Demo
Toast Notifications
Use toasts for transient errors that can be retried or dismissed.
Error Modal with Debug Info
Use modals for errors requiring user attention with detailed debug information.
Usage Guidelines
When to use Toasts
- • Network connectivity issues
- • Request timeouts
- • Rate limiting
- • Transient server errors
- • Success confirmations
When to use Modals
- • Unrecoverable errors
- • Errors requiring debug info
- • Validation failures with details
- • Errors needing user action
- • Support ticket scenarios
Implementation
Toast Component
Wrap your app with ToastProvider and use the useToast hook:
import { ToastProvider, useToast } from '@/components/ui/toast';
function App() {
return (
<ToastProvider>
<YourContent />
</ToastProvider>
);
}
function YourContent() {
const { addToast } = useToast();
const handleError = () => {
addToast({
title: 'Error',
description: 'Something went wrong',
variant: 'error',
action: {
label: 'Retry',
onClick: () => retry(),
},
});
};
}Error Modal
Display detailed error information with copy-to-clipboard:
import { ErrorModal } from '@/components/ui/error-modal';
<ErrorModal
open={isOpen}
onClose={() => setIsOpen(false)}
title="Server Error"
message="An error occurred"
errorDetails={
endpoint: '/api/data',
method: 'POST',
status: 500,
statusText: 'Internal Server Error',
timestamp: new Date().toISOString(),
requestId: 'req_abc123',
}
/>ApiErrorDetails Interface
interface ApiErrorDetails {
endpoint: string;
method: string;
payload?: unknown;
status?: number;
statusText?: string;
response?: unknown;
timestamp: string;
requestId?: string;
}Best Practices
- • Auto-dismiss toasts after 5 seconds
- • Include retry actions for transient errors
- • Provide request IDs for support tickets
- • Sanitize sensitive data before display
- • Use appropriate color coding for severity
Key Exports
ToastProvider- Context provideruseToast()- Hook for toast actionsErrorModal- Modal componentApiErrorDetails- TypeScript interface