JsGuide

Learn JavaScript with practical tutorials and code examples

Code Snippet Intermediate
• Updated Jan 22, 2025

JavaScript Error Handling Code Snippets and Utilities

Ready-to-use JavaScript error handling utilities and code snippets for robust application development and debugging.

JavaScript Error Handling Code Snippets and Utilities

JavaScript error handling is crucial for building robust applications. These ready-to-use code snippets provide comprehensive error handling utilities that you can integrate into your projects immediately.

Basic Error Wrapper Function #

This utility wraps any function with comprehensive JavaScript error handling:

Async Error Handler Utility #

Handle JavaScript errors in asynchronous operations with this utility:

// Async error handler for promises
async function asyncSafeExecute(asyncFn, retries = 3) {
    for (let attempt = 1; attempt <= retries; attempt++) {
        try {
            const result = await asyncFn();
            return { success: true, data: result, error: null, attempts: attempt };
        } catch (error) {
            console.error(`JavaScript Error on attempt ${attempt}:`, error.message);
            
            if (attempt === retries) {
                return { success: false, data: null, error: error, attempts: attempt };
            }
            
            // Wait before retry
            await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
        }
    }
}

Error Logger Utility #

A comprehensive JavaScript error logging utility:

Form Validation Error Handler #

Specialized JavaScript error handling for form validation:

// Form validation with error handling
class FormValidator {
    constructor(formElement) {
        this.form = formElement;
        this.errors = {};
    }
    
    validateField(fieldName, value, rules) {
        this.errors[fieldName] = [];
        
        for (const rule of rules) {
            try {
                if (!rule.validator(value)) {
                    this.errors[fieldName].push(rule.message);
                }
            } catch (error) {
                console.error(`JavaScript Error in validation rule for ${fieldName}:`, error);
                this.errors[fieldName].push('Validation error occurred');
            }
        }
        
        return this.errors[fieldName].length === 0;
    }
    
    hasErrors() {
        return Object.values(this.errors).some(errorArray => errorArray.length > 0);
    }
    
    getErrors() {
        return this.errors;
    }
}

API Error Handler Utility #

Handle JavaScript errors in API calls with this comprehensive utility:

Error Boundary Utility for Components #

JavaScript error boundary pattern for component-based applications:

// Error boundary utility for components
class ErrorBoundary {
    constructor() {
        this.hasError = false;
        this.error = null;
        this.errorInfo = null;
    }
    
    catchError(error, errorInfo = {}) {
        this.hasError = true;
        this.error = error;
        this.errorInfo = errorInfo;
        
        console.error('JavaScript Error caught by boundary:', {
            error: error.message,
            stack: error.stack,
            componentStack: errorInfo.componentStack,
            timestamp: new Date().toISOString()
        });
        
        // You can send error reports here
        this.reportError(error, errorInfo);
    }
    
    reportError(error, errorInfo) {
        // Simulate error reporting
        const errorReport = {
            message: error.message,
            stack: error.stack,
            url: window.location.href,
            userAgent: navigator.userAgent,
            timestamp: new Date().toISOString(),
            ...errorInfo
        };
        
        console.log('Error report generated:', errorReport);
    }
    
    reset() {
        this.hasError = false;
        this.error = null;
        this.errorInfo = null;
    }
}

Custom Error Types #

Create custom JavaScript error types for better error categorization:

Error Recovery Utility #

Implement error recovery patterns with this utility:

// Error recovery utility
class ErrorRecovery {
    static withFallback(primaryFn, fallbackFn, context = '') {
        try {
            return primaryFn();
        } catch (error) {
            console.warn(`JavaScript Error in primary function (${context}):`, error.message);
            console.log('Attempting fallback...');
            
            try {
                return fallbackFn();
            } catch (fallbackError) {
                console.error(`JavaScript Error in fallback function (${context}):`, fallbackError.message);
                throw new Error(`Both primary and fallback functions failed: ${error.message} | ${fallbackError.message}`);
            }
        }
    }
    
    static withRetry(fn, maxRetries = 3, delay = 1000) {
        return new Promise(async (resolve, reject) => {
            for (let attempt = 1; attempt <= maxRetries; attempt++) {
                try {
                    const result = await fn();
                    resolve(result);
                    return;
                } catch (error) {
                    console.error(`JavaScript Error on attempt ${attempt}/${maxRetries}:`, error.message);
                    
                    if (attempt === maxRetries) {
                        reject(error);
                        return;
                    }
                    
                    await new Promise(resolve => setTimeout(resolve, delay * attempt));
                }
            }
        });
    }
}

Integration Tips #

Using These Utilities #

  1. Import the utilities you need into your project
  2. Wrap critical functions with the safeExecute utility
  3. Implement error logging throughout your application
  4. Use custom error types for better error categorization
  5. Set up error boundaries in your component architecture

Best Practices #

  • Always handle JavaScript errors at the appropriate level
  • Use specific error types for different error categories
  • Implement proper error logging and reporting
  • Provide meaningful error messages to users
  • Test error handling paths thoroughly

These JavaScript error handling utilities provide a solid foundation for robust error management in your applications.

Related Snippets

Snippet Intermediate

JavaScript Main Process Error Handler Code Snippets

Ready-to-use JavaScript code snippets for handling main process errors with robust error detection and recovery utilities.

#javascript #error-handling #main-process +2
View Code
Syntax
Snippet Beginner

How to Fix JavaScript Error: Ready-to-Use Utilities

Practical JavaScript code snippets and utilities to quickly fix common JavaScript errors with copy-paste solutions.

#javascript #error #fix +2
View Code
Syntax
Snippet Intermediate

Fix Async Await Promise Pending - Code Utilities

Ready-to-use JavaScript functions to fix async await promise pending issues with comprehensive error handling and debugging tools.

#javascript #async #await +2
View Code
Syntax
Snippet Intermediate

JavaScript Code Snippets: Fix 'ipython is not defined' Error

Ready-to-use JavaScript code snippets to handle and fix 'ipython is not defined' errors in Jupyter notebooks and web environments.

#javascript #ipython #error-handling +2
View Code
Syntax