I'll show you how to implement a generic error modal system that handles errors thrown in middleware. The key is to use a combination of middleware error handling, cookies/headers, and a global error modal component.
This implementation provides a comprehensive error handling system for middleware errors:
Key Features:
- Middleware Error Handling: The middleware catches errors and stores them in cookies that the client can read
- Global Error Context: A React context manages error state across the application
- Error Modal Component: A reusable modal that displays errors to users
- Automatic Error Detection: The system automatically checks for middleware errors on page load and route changes
- Multiple Error Sources: Handles errors from middleware, API calls, and client-side code
How It Works:
- Middleware: Catches errors and sets a cookie with error information
- Error Provider: Checks for error cookies and manages global error state
- Error Modal: Displays errors in a user-friendly modal dialog
- Automatic Cleanup: Error cookies are automatically cleared after being read
Usage Examples:
- Protected Routes: Try accessing
/dashboard without authentication - Invalid Tokens: Test with invalid authentication tokens
- API Errors: Simulate API failures
- Client Errors: Trigger client-side errors manually
The system gracefully handles all error scenarios and provides consistent user feedback through the modal interface.