File size: 7,330 Bytes
3d50167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcbb712
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d50167
 
 
 
 
 
 
bcbb712
 
 
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
// ===== KIMI ERROR MANAGEMENT SYSTEM =====
class KimiErrorManager {
    constructor() {
        this.errorLog = [];
        this.maxLogSize = 100;
        this.errorHandlers = new Map();
        this.setupGlobalHandlers();
    }

    setupGlobalHandlers() {
        // Handle unhandled promise rejections
        window.addEventListener("unhandledrejection", event => {
            this.logError("UnhandledPromiseRejection", event.reason, {
                promise: event.promise,
                timestamp: new Date().toISOString()
            });
            event.preventDefault();
        });

        // Handle JavaScript errors
        window.addEventListener("error", event => {
            this.logError("JavaScriptError", event.error || event.message, {
                filename: event.filename,
                lineno: event.lineno,
                colno: event.colno,
                timestamp: new Date().toISOString()
            });
        });
    }

    logError(type, error, context = {}) {
        const errorEntry = {
            id: this.generateErrorId(),
            type,
            message: error?.message || error,
            stack: error?.stack,
            context,
            timestamp: new Date().toISOString(),
            severity: this.determineSeverity(type, error)
        };

        this.errorLog.push(errorEntry);

        // Keep log size manageable
        if (this.errorLog.length > this.maxLogSize) {
            this.errorLog.shift();
        }

        // Console logging with appropriate level
        this.consoleLog(errorEntry);

        // Trigger registered handlers
        this.triggerHandlers(errorEntry);

        return errorEntry.id;
    }

    generateErrorId() {
        return "err_" + Date.now() + "_" + Math.random().toString(36).substr(2, 9);
    }

    determineSeverity(type, error) {
        const criticalTypes = ["UnhandledPromiseRejection", "DatabaseError", "InitializationError"];
        const criticalMessages = ["failed to fetch", "network error", "connection refused"];

        if (criticalTypes.includes(type)) return "critical";

        const message = (error?.message || error || "").toLowerCase();
        if (criticalMessages.some(cm => message.includes(cm))) return "critical";

        return "warning";
    }

    consoleLog(errorEntry) {
        const { type, message, severity, context } = errorEntry;

        switch (severity) {
            case "critical":
                console.error(`🚨 [${type}]`, message, context);
                break;
            case "warning":
                console.warn(`⚠️ [${type}]`, message, context);
                break;
            default:
                console.info(`ℹ️ [${type}]`, message, context);
        }
    }

    triggerHandlers(errorEntry) {
        const handlers = this.errorHandlers.get(errorEntry.type) || [];
        handlers.forEach(handler => {
            try {
                handler(errorEntry);
            } catch (handlerError) {
                console.error("Error in error handler:", handlerError);
            }
        });
    }

    registerHandler(errorType, handler) {
        if (!this.errorHandlers.has(errorType)) {
            this.errorHandlers.set(errorType, []);
        }
        this.errorHandlers.get(errorType).push(handler);
    }

    unregisterHandler(errorType, handler) {
        const handlers = this.errorHandlers.get(errorType);
        if (handlers) {
            const index = handlers.indexOf(handler);
            if (index > -1) {
                handlers.splice(index, 1);
            }
        }
    }

    getErrorLog(filter = null) {
        if (!filter) return [...this.errorLog];

        return this.errorLog.filter(entry => {
            if (filter.type && entry.type !== filter.type) return false;
            if (filter.severity && entry.severity !== filter.severity) return false;
            if (filter.since && new Date(entry.timestamp) < filter.since) return false;
            return true;
        });
    }

    clearErrorLog() {
        this.errorLog.length = 0;
    }

    // Helper methods for different error types
    logInitError(component, error, context = {}) {
        return this.logError("InitializationError", error, { component, ...context });
    }

    logDatabaseError(operation, error, context = {}) {
        return this.logError("DatabaseError", error, { operation, ...context });
    }

    logAPIError(endpoint, error, context = {}) {
        return this.logError("APIError", error, { endpoint, ...context });
    }

    logValidationError(field, error, context = {}) {
        return this.logError("ValidationError", error, { field, ...context });
    }

    logUIError(component, error, context = {}) {
        return this.logError("UIError", error, { component, ...context });
    }

    // Async wrapper for functions
    async wrapAsync(fn, errorContext = {}) {
        try {
            return await fn();
        } catch (error) {
            this.logError("AsyncOperationError", error, errorContext);
            throw error;
        }
    }

    // Sync wrapper for functions
    wrapSync(fn, errorContext = {}) {
        try {
            return fn();
        } catch (error) {
            this.logError("SyncOperationError", error, errorContext);
            throw error;
        }
    }

    // Debug helpers for development
    getErrorSummary() {
        const summary = {
            totalErrors: this.errorLog.length,
            critical: this.errorLog.filter(e => e.severity === "critical").length,
            warning: this.errorLog.filter(e => e.severity === "warning").length,
            recent: this.errorLog.filter(e => {
                const errorTime = new Date(e.timestamp);
                const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);
                return errorTime > fiveMinutesAgo;
            }).length,
            types: [...new Set(this.errorLog.map(e => e.type))]
        };
        return summary;
    }

    printErrorSummary() {
        const summary = this.getErrorSummary();
        console.group("πŸ” Kimi Error Manager Summary");
        console.log(`πŸ“Š Total Errors: ${summary.totalErrors}`);
        console.log(`🚨 Critical: ${summary.critical}`);
        console.log(`⚠️ Warnings: ${summary.warning}`);
        console.log(`⏰ Recent (5min): ${summary.recent}`);
        console.log(`πŸ“‹ Error Types:`, summary.types);
        if (summary.totalErrors > 0) {
            console.log(`πŸ’‘ Use kimiErrorManager.getErrorLog() to see details`);
        }
        console.groupEnd();
        return summary;
    }

    clearAndSummarize() {
        const summary = this.getErrorSummary();
        this.clearErrorLog();
        console.log("🧹 Error log cleared. Previous summary:", summary);
        return summary;
    }
}

// Create global instance
window.kimiErrorManager = new KimiErrorManager();

// Export class for manual instantiation if needed
window.KimiErrorManager = KimiErrorManager;

// Global debugging helper
window.kimiDebugErrors = () => window.kimiErrorManager.printErrorSummary();