Jake Vanderwerf
2025-11-04 42fa8304ddb811b0f725f245130f70c0f5e86a6c
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/**
 * 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
     */
    async logErrorToServer(type, message, context) {
        try {
            if (!this.options.apiUrl) return;
 
            const data = new FormData();
            data.append('error_type', type);
            data.append('message', message);
            data.append('context', JSON.stringify({
                ...context,
                url: window.location.href,
                userAgent: navigator.userAgent,
                timestamp: new Date().toISOString()
            }));
 
            // Use fetch with no-cors to ensure this always succeeds
            // even if there are CORS issues
            await fetch(`${this.options.apiUrl}errors/log`, {
                method: 'POST',
                headers: {
                    'X-WP-Nonce': window.feedSettings?.nonce || ''
                },
                body: data
            });
        } catch (e) {
            // Silently fail - we don't want errors in error reporting
            console.warn('Failed to log error to server', e);
        }
    }
 
    /**
     * 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.feedSettings && window.feedSettings.loginUrl) {
            window.location.href = window.feedSettings.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);
 
        // Display retry notification
        if (this.options.displayNotifications) {
            this.displayRetryNotification(backoffTime);
        }
 
        // Wait before retrying
        await new Promise(resolve => setTimeout(resolve, backoffTime));
 
        // Try again
        return callback();
    }
 
    /**
     * Display retry notification
     */
    displayRetryNotification(backoffTime) {
        if (window.jvbNotifications) {
            window.jvbNotifications.queuePopupNotification({
                type: 'info',
                message: `Retrying in ${backoffTime/1000} seconds...`,
                icon: 'refresh',
                priority: 'medium',
                displayDuration: backoffTime
            });
        }
    }
 
    /**
     * Reset retry counter
     */
    resetRetryCount() {
        this.retryCount = 0;
    }
 
    /**
     * Handle user feedback for errors
     */
    collectUserFeedback(errorInfo) {
        // Create a modal for collecting feedback
        const modal = document.createElement('dialog');
        modal.className = 'error-feedback-modal';
 
        modal.innerHTML = `
            <h2>Help Us Improve</h2>
            <p>We encountered an error. Would you like to tell us what happened?</p>
            <form method="dialog" data-save="error">
                <textarea placeholder="What were you trying to do when this error occurred?"></textarea>
                <div class="actions">
                    <button value="cancel">Skip</button>
                    <button value="submit" class="primary">Send Feedback</button>
                </div>
            </form>
        `;
 
        document.body.appendChild(modal);
 
        return new Promise((resolve) => {
            modal.addEventListener('close', () => {
                const feedback = modal.returnValue === 'submit'
                    ? modal.querySelector('textarea').value
                    : null;
 
                document.body.removeChild(modal);
                resolve(feedback);
            });
 
            modal.showModal();
        });
    }
 
    /**
     * Handle global errors
     */
    setupGlobalErrorHandling() {
        // Handle uncaught errors
        window.addEventListener('error', event => {
            this.log(
                event.error || new Error(event.message),
                {
                    message: event.message,
                    filename: event.filename,
                    lineno: event.lineno,
                    colno: event.colno,
                    type: 'global_error'
                }
            );
 
            // Don't prevent default - let browser show its own error if needed
        });
 
        // Handle unhandled promise rejections
        window.addEventListener('unhandledrejection', event => {
            this.log(
                event.reason,
                {
                    type: 'unhandled_promise',
                    message: event.reason?.message || 'Unhandled promise rejection'
                }
            );
        });
    }
}
document.addEventListener('DOMContentLoaded', function () {
    window.jvbError = new ErrorHandler({
        api: jvbSettings.api,
        logToServer: true,
        displayNotifications: true,
        notificationDuration: 5000,
        retryEnabled: true,
        maxRetries: 3
    });
});