error-handlers.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Global error handlers to prevent freezing
  2. if (typeof window !== 'undefined') {
  3. // Handle unhandled promise rejections
  4. window.addEventListener('unhandledrejection', (event) => {
  5. console.error('Unhandled promise rejection:', event.reason);
  6. // Prevent the error from causing the app to freeze
  7. event.preventDefault();
  8. // Optionally show a user-friendly notification
  9. if (event.reason instanceof Error && event.reason.message) {
  10. console.warn('Application error:', event.reason.message);
  11. }
  12. });
  13. // Handle uncaught errors
  14. window.addEventListener('error', (event) => {
  15. console.error('Uncaught error:', event.error);
  16. // Prevent the error from causing the app to freeze
  17. event.preventDefault();
  18. });
  19. // Handle resource loading errors
  20. window.addEventListener('error', (event) => {
  21. if (event.target !== window) {
  22. console.warn('Resource loading error:', event.target);
  23. event.preventDefault();
  24. }
  25. }, true);
  26. }
  27. // Export a utility function for manual error reporting
  28. export function reportError(error: Error, context?: string) {
  29. console.error(`Application error${context ? ` in ${context}` : ''}:`, error);
  30. // In development, you might want to show more details
  31. if (process.env.NODE_ENV === 'development') {
  32. console.trace('Error stack trace');
  33. }
  34. }
  35. // Export a function to safely run async operations
  36. export async function safeAsync<T>(
  37. operation: () => Promise<T>,
  38. fallback?: T,
  39. context?: string
  40. ): Promise<T | undefined> {
  41. try {
  42. return await operation();
  43. } catch (error) {
  44. reportError(error instanceof Error ? error : new Error(String(error)), context);
  45. return fallback;
  46. }
  47. }
  48. // Export a function to safely run sync operations
  49. export function safeSync<T>(
  50. operation: () => T,
  51. fallback?: T,
  52. context?: string
  53. ): T | undefined {
  54. try {
  55. return operation();
  56. } catch (error) {
  57. reportError(error instanceof Error ? error : new Error(String(error)), context);
  58. return fallback;
  59. }
  60. }