How to append new information and rethrowing errors in nested functions in JavaScript?

In JavaScript, appending new information to errors and rethrowing them in nested functions helps create more informative error messages while preserving the original error details. This technique is essential for debugging complex applications with multiple function layers.

Understanding Error Rethrowing

Error rethrowing allows us to catch an error, add contextual information, and throw it again to be handled at a higher level. This maintains the error chain while providing additional debugging context.

Basic Error Rethrowing

Here's how to rethrow an error with additional information:

function innerFunction() {
    throw new Error("Original error occurred");
}

function outerFunction() {
    try {
        innerFunction();
    } catch (error) {
        // Append new information and rethrow
        error.message = `Outer function context: ${error.message}`;
        error.location = "outerFunction";
        throw error;
    }
}

try {
    outerFunction();
} catch (error) {
    console.log("Final error:", error.message);
    console.log("Location:", error.location);
}
Final error: Outer function context: Original error occurred
Location: outerFunction

Creating Enhanced Error Objects

For more structured error handling, create new error objects that wrap the original error:

function processData(data) {
    if (!data) {
        throw new Error("Data is null or undefined");
    }
    return data.toUpperCase();
}

function validateAndProcess(input) {
    try {
        return processData(input);
    } catch (originalError) {
        // Create enhanced error with additional context
        const enhancedError = new Error(`Validation failed: ${originalError.message}`);
        enhancedError.originalError = originalError;
        enhancedError.input = input;
        enhancedError.timestamp = new Date().toISOString();
        throw enhancedError;
    }
}

try {
    validateAndProcess(null);
} catch (error) {
    console.log("Enhanced error:", error.message);
    console.log("Original error:", error.originalError.message);
    console.log("Input value:", error.input);
    console.log("Timestamp:", error.timestamp);
}
Enhanced error: Validation failed: Data is null or undefined
Original error: Data is null or undefined
Input value: null
Timestamp: 2024-01-15T10:30:45.123Z

Nested Function Error Chain

When working with multiple nested functions, maintain the error chain at each level:

function databaseQuery() {
    throw new Error("Database connection failed");
}

function fetchUser(userId) {
    try {
        return databaseQuery();
    } catch (error) {
        error.message = `fetchUser(${userId}): ${error.message}`;
        error.userId = userId;
        throw error;
    }
}

function getUserProfile(userId) {
    try {
        return fetchUser(userId);
    } catch (error) {
        error.message = `getUserProfile: ${error.message}`;
        error.context = "user profile retrieval";
        throw error;
    }
}

try {
    getUserProfile(123);
} catch (error) {
    console.log("Error chain:", error.message);
    console.log("User ID:", error.userId);
    console.log("Context:", error.context);
}
Error chain: getUserProfile: fetchUser(123): Database connection failed
User ID: 123
Context: user profile retrieval

Best Practices

Practice Description Benefit
Preserve Original Error Keep reference to original error object Maintains stack trace
Add Context Information Include function parameters and state Better debugging
Use Descriptive Messages Append meaningful context to error messages Clearer error identification

Conclusion

Appending information to errors and rethrowing them in nested functions creates a clear error trail that helps developers quickly identify and fix issues. Always preserve the original error while adding contextual information at each function level.

Updated on: 2026-03-15T23:19:00+05:30

407 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements