Jake Vanderwerf
2026-05-12 16cb63b05910055c31dca821c86f2eb815da99e3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/**
 * ErrorHandlingService.js - Centralized error handling for the feed block
 */
class ErrorHandler {
    constructor(options = {}) {
        this.options = {
            apiUrl: '',
            logToServer: true,
            displayNotifications: true,
            notificationDuration: 5000,
            retryEnabled: true,
            maxRetries: 3,
            ...options
        };
 
        this.retryCount = 0;
    }
 
    /**
     * Handle API errors
     * @param {Error} error - The error object
     * @param {Object} context - Additional context information
     * @param {Function} retryCallback - Function to retry the operation
     * @returns {Promise} - Result of error handling
     */
    async log(error, context = {}, retryCallback = null) {
        // Log error to console
        console.error('API Error:', error, context);
 
        // Determine error type and message
        const errorType = this.getErrorType(error);
        const errorMessage = this.getErrorMessage(error, errorType);
 
        // Log to server if enabled
        if (this.options.logToServer) {
            await this.logErrorToServer(errorType, errorMessage, context);
        }
 
        // Handle specific error types
        switch (errorType) {
            case 'network':
                // Check if we should retry
                if (this.options.retryEnabled && this.retryCount < this.options.maxRetries && retryCallback) {
                    this.retryCount++;
                    return this.retryWithBackoff(retryCallback);
                }
                break;
 
            case 'auth':
                // Handle authentication errors - possibly redirect to login
                this.handleAuthError();
                break;
 
            case 'rate_limit':
                // Handle rate limiting
                return this.handleRateLimitError(retryCallback);
 
            case 'server':
                // Server errors may be temporary
                if (this.options.retryEnabled && this.retryCount < this.options.maxRetries && retryCallback) {
                    this.retryCount++;
                    return this.retryWithBackoff(retryCallback);
                }
                break;
        }
 
        // Display error notification if enabled
        if (this.options.displayNotifications) {
            this.displayErrorNotification(errorMessage, errorType, retryCallback);
        }
 
        // Reset retry count if we're not retrying
        if (!retryCallback || !this.options.retryEnabled) {
            this.retryCount = 0;
        }
 
        // Return standardized error object
        return {
            success: false,
            error: errorType,
            message: errorMessage,
            context
        };
    }
 
    /**
     * Get error type based on error object
     */
    getErrorType(error) {
        if (error.name === 'AbortError') {
            return 'timeout';
        }
 
        if (!navigator.onLine) {
            return 'offline';
        }
 
        if (error.response) {
            const status = error.response.status;
 
            if (status >= 400 && status < 500) {
                if (status === 401 || status === 403) {
                    return 'auth';
                }
                if (status === 429) {
                    return 'rate_limit';
                }
                return 'client';
            }
 
            if (status >= 500) {
                return 'server';
            }
        }
 
        return 'network';
    }
 
    /**
     * Get user-friendly error message
     */
    getErrorMessage(error, type) {
        const defaultMessages = {
            network: "We couldn't connect to the server. Please check your connection and try again.",
            timeout: "The request took too long to complete. Please try again.",
            offline: "You appear to be offline. Please check your internet connection.",
            auth: "Your session may have expired. Please log in again.",
            rate_limit: "You've made too many requests. Please wait a moment and try again.",
            server: "We're experiencing technical difficulties. Please try again later.",
            client: "Something went wrong with your request. Please try again.",
            unknown: "An unexpected error occurred. Please try again."
        };
 
        // Try to get message from error object
        if (error.response && error.response.data && error.response.data.message) {
            return error.response.data.message;
        }
 
        if (error.message) {
            return error.message;
        }
 
        // Fall back to default message
        return defaultMessages[type] || defaultMessages.unknown;
    }
 
    /**
     * Log error to server with enhanced context
     */
    async logErrorToServer(type, message, context) {
        try {
            if (!this.options.apiUrl) return;
 
            // Enhanced context with component tracking
            const enhancedContext = {
                ...context,
                url: window.location.href,
                pathname: window.location.pathname,
                userAgent: navigator.userAgent,
                timestamp: new Date().toISOString(),
                viewport: `${window.innerWidth}x${window.innerHeight}`,
                component: context.component || this.extractComponentFromStack(context.stack),
                method: context.method || this.extractMethodFromStack(context.stack),
                stack: context.stack || (context.error?.stack),
                isLoggedIn: window.auth.isAuthenticated(),
                source: 'frontend'
            };
 
            const data = new FormData();
            data.append('error_type', type);
            data.append('message', message);
            data.append('context', JSON.stringify(enhancedContext));
 
            await fetch(`${this.options.apiUrl}errors/log`, {
                method: 'POST',
                headers: {
                    'X-WP-Nonce': window.auth.getNonce()
                },
                body: data
            });
        } catch (e) {
            console.warn('Failed to log error to server', e);
        }
    }
 
    /**
     * Extract component name from error stack
     */
    extractComponentFromStack(stack) {
        if (!stack) return 'Unknown';
 
        // Try to extract class/component name from stack trace
        const match = stack.match(/at\s+(\w+)\./);
        return match ? match[1] : 'Unknown';
    }
 
    /**
     * Extract method name from error stack
     */
    extractMethodFromStack(stack) {
        if (!stack) return null;
 
        // Try to extract method name
        const match = stack.match(/at\s+\w+\.(\w+)\s+/);
        return match ? match[1] : null;
    }
 
    /**
     * Display error notification
     */
    displayErrorNotification(message, type, retryCallback) {
        // Use WordPress notification system if available
        if (window.jvbNotifications) {
            const actions = [];
 
            // Add retry action if callback provided
            if (retryCallback) {
                actions.push({
                    label: 'Try Again',
                    icon: 'refresh',
                    action: retryCallback
                });
            }
 
            window.jvbNotifications.queuePopupNotification({
                type: 'error',
                message: message,
                icon: 'alert',
                priority: 'high',
                displayDuration: this.options.notificationDuration,
                actions: actions
            });
            return;
        }
 
        // Fallback to basic alert if notification system not available
        alert(message);
    }
 
    /**
     * Handle authentication errors
     */
    handleAuthError() {
        // Redirect to login page if user isn't logged in
        if (window.jvbSettings && window.jvbSettings.loginUrl) {
            window.location.href = window.jvbSettings.loginUrl;
            return;
        }
 
        // Or reload the page to refresh session
        window.location.reload();
    }
 
    /**
     * Handle rate limit errors
     */
    async handleRateLimitError(retryCallback) {
        // Wait for escalating periods before retrying
        const waitTime = 2000 * (this.retryCount + 1);
 
        await new Promise(resolve => setTimeout(resolve, waitTime));
 
        if (retryCallback) {
            this.retryCount++;
            return retryCallback();
        }
    }
 
    /**
     * Retry with exponential backoff
     */
    async retryWithBackoff(callback) {
        const backoffTime = Math.min(1000 * Math.pow(2, this.retryCount), 10000);
 
        // Wait before retrying
        await new Promise(resolve => setTimeout(resolve, backoffTime));
 
        // Try again
        return callback();
    }
 
 
    /**
     * Reset retry counter
     */
    resetRetryCount() {
        this.retryCount = 0;
    }
}
document.addEventListener('DOMContentLoaded', async function () {
    window.auth.subscribe((event) => {
        if (event === 'auth-loaded') {
            window.jvbError = new ErrorHandler({
                api: jvbSettings.api,
                logToServer: true,
                displayNotifications: true,
                notificationDuration: 5000,
                retryEnabled: true,
                maxRetries: 3
            });
        }
    });
 
});