| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- // Global error handlers to prevent freezing
- if (typeof window !== 'undefined') {
- // Handle unhandled promise rejections
- window.addEventListener('unhandledrejection', (event) => {
- console.error('Unhandled promise rejection:', event.reason);
-
- // Prevent the error from causing the app to freeze
- event.preventDefault();
-
- // Optionally show a user-friendly notification
- if (event.reason instanceof Error && event.reason.message) {
- console.warn('Application error:', event.reason.message);
- }
- });
- // Handle uncaught errors
- window.addEventListener('error', (event) => {
- console.error('Uncaught error:', event.error);
-
- // Prevent the error from causing the app to freeze
- event.preventDefault();
- });
- // Handle resource loading errors
- window.addEventListener('error', (event) => {
- if (event.target !== window) {
- console.warn('Resource loading error:', event.target);
- event.preventDefault();
- }
- }, true);
- }
- // Export a utility function for manual error reporting
- export function reportError(error: Error, context?: string) {
- console.error(`Application error${context ? ` in ${context}` : ''}:`, error);
-
- // In development, you might want to show more details
- if (process.env.NODE_ENV === 'development') {
- console.trace('Error stack trace');
- }
- }
- // Export a function to safely run async operations
- export async function safeAsync<T>(
- operation: () => Promise<T>,
- fallback?: T,
- context?: string
- ): Promise<T | undefined> {
- try {
- return await operation();
- } catch (error) {
- reportError(error instanceof Error ? error : new Error(String(error)), context);
- return fallback;
- }
- }
- // Export a function to safely run sync operations
- export function safeSync<T>(
- operation: () => T,
- fallback?: T,
- context?: string
- ): T | undefined {
- try {
- return operation();
- } catch (error) {
- reportError(error instanceof Error ? error : new Error(String(error)), context);
- return fallback;
- }
- }
|