File size: 11,554 Bytes
857cdcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/**
 *  Chahuadev Framework - Error Handler Module
 * Error Detection, Logging & Debugging Support
 * 
 *  Chahua Development Thailand
 *  CEO: Saharath C.
 *  www.chahuadev.com
 */

const fs = require('fs');
const path = require('path');

class ErrorHandler {
    constructor() {
        this.errorTypes = {
            VALIDATION: 'validation',
            SECURITY: 'security',
            EXECUTION: 'execution',
            SYSTEM: 'system',
            NETWORK: 'network',
            BRIDGE: 'bridge',
            CONTEXT: 'context'
        };

        this.logFile = path.join(process.cwd(), 'logs', 'errors.log');
        this.debugMode = process.env.DEBUG === 'true' || process.env.NODE_ENV === 'development';
        
        this.ensureLogDirectory();
        console.log(' Error Handler initialized');
    }

    /**
     * Handle and log error
     * @param {Error|string} error - Error object or message
     * @param {string} type - Error type
     * @param {Object} context - Pipeline context
     * @param {Object} metadata - Additional metadata
     * @returns {Object} Processed error info
     */
    handle(error, type = this.errorTypes.SYSTEM, context = null, metadata = {}) {
        const errorInfo = this.processError(error, type, context, metadata);
        
        // Log error
        this.log(errorInfo);
        
        // Console output based on debug mode
        if (this.debugMode) {
            this.debugOutput(errorInfo);
        } else {
            console.error(` ${errorInfo.type}: ${errorInfo.message}`);
        }

        return errorInfo;
    }

    /**
     * Process error into standardized format
     * @private
     * @param {Error|string} error - Error object or message
     * @param {string} type - Error type
     * @param {Object} context - Pipeline context
     * @param {Object} metadata - Additional metadata
     * @returns {Object} Processed error info
     */
    processError(error, type, context, metadata) {
        const timestamp = new Date().toISOString();
        const errorId = this.generateErrorId();

        let errorInfo = {
            id: errorId,
            timestamp: timestamp,
            type: type,
            message: '',
            stack: null,
            code: null,
            details: {},
            context: null,
            metadata: metadata || {}
        };

        // Extract error information
        if (error instanceof Error) {
            errorInfo.message = error.message;
            errorInfo.stack = error.stack;
            errorInfo.code = error.code || null;
            
            // Extract additional error properties
            if (error.errno) errorInfo.details.errno = error.errno;
            if (error.syscall) errorInfo.details.syscall = error.syscall;
            if (error.path) errorInfo.details.path = error.path;
        } else {
            errorInfo.message = String(error);
        }

        // Add context information
        if (context) {
            errorInfo.context = {
                pipelineId: context.pipelineId,
                pipelineType: context.pipelineType,
                currentStep: context.steps.length > 0 ? 
                    context.steps[context.steps.length - 1].stepName : 'unknown',
                executionStatus: context.execution.status,
                systemType: context.systemInfo.detectedType
            };
        }

        // Add environment information
        errorInfo.environment = {
            nodeVersion: process.version,
            platform: process.platform,
            arch: process.arch,
            memory: process.memoryUsage(),
            uptime: process.uptime()
        };

        return errorInfo;
    }

    /**
     * Log error to file
     * @private
     * @param {Object} errorInfo - Processed error information
     */
    log(errorInfo) {
        try {
            const logEntry = JSON.stringify(errorInfo) + '\n';
            fs.appendFileSync(this.logFile, logEntry, 'utf8');
        } catch (logError) {
            console.error('Failed to write error log:', logError.message);
        }
    }

    /**
     * Debug output to console
     * @private
     * @param {Object} errorInfo - Processed error information
     */
    debugOutput(errorInfo) {
        console.error('\n=== CHAHUADEV ERROR DEBUG ===');
        console.error(` Error ID: ${errorInfo.id}`);
        console.error(` Timestamp: ${errorInfo.timestamp}`);
        console.error(`  Type: ${errorInfo.type}`);
        console.error(` Message: ${errorInfo.message}`);
        
        if (errorInfo.context) {
            console.error(` Pipeline: ${errorInfo.context.pipelineId}`);
            console.error(` Step: ${errorInfo.context.currentStep}`);
        }
        
        if (errorInfo.stack && this.debugMode) {
            console.error(` Stack Trace:\n${errorInfo.stack}`);
        }
        
        if (Object.keys(errorInfo.details).length > 0) {
            console.error(' Details:', errorInfo.details);
        }
        
        console.error('========================\n');
    }

    /**
     * Create validation error
     * @param {string} message - Error message
     * @param {Object} context - Pipeline context
     * @param {Object} validationData - Validation specific data
     * @returns {Object} Error info
     */
    validation(message, context = null, validationData = {}) {
        return this.handle(
            new Error(message), 
            this.errorTypes.VALIDATION, 
            context, 
            { validationData }
        );
    }

    /**
     * Create security error
     * @param {string} message - Error message
     * @param {Object} context - Pipeline context
     * @param {Object} securityData - Security specific data
     * @returns {Object} Error info
     */
    security(message, context = null, securityData = {}) {
        return this.handle(
            new Error(message), 
            this.errorTypes.SECURITY, 
            context, 
            { securityData }
        );
    }

    /**
     * Create execution error
     * @param {string} message - Error message
     * @param {Object} context - Pipeline context
     * @param {Object} executionData - Execution specific data
     * @returns {Object} Error info
     */
    execution(message, context = null, executionData = {}) {
        return this.handle(
            new Error(message), 
            this.errorTypes.EXECUTION, 
            context, 
            { executionData }
        );
    }

    /**
     * Create bridge communication error
     * @param {string} message - Error message
     * @param {Object} context - Pipeline context
     * @param {Object} bridgeData - Bridge specific data
     * @returns {Object} Error info
     */
    bridge(message, context = null, bridgeData = {}) {
        return this.handle(
            new Error(message), 
            this.errorTypes.BRIDGE, 
            context, 
            { bridgeData }
        );
    }

    /**
     * Create context error
     * @param {string} message - Error message
     * @param {Object} context - Pipeline context
     * @param {Object} contextData - Context specific data
     * @returns {Object} Error info
     */
    context(message, context = null, contextData = {}) {
        return this.handle(
            new Error(message), 
            this.errorTypes.CONTEXT, 
            context, 
            { contextData }
        );
    }

    /**
     * Wrap function with error handling
     * @param {Function} fn - Function to wrap
     * @param {string} errorType - Error type for this function
     * @param {Object} context - Pipeline context
     * @returns {Function} Wrapped function
     */
    wrap(fn, errorType = this.errorTypes.SYSTEM, context = null) {
        return async (...args) => {
            try {
                return await fn(...args);
            } catch (error) {
                this.handle(error, errorType, context, { 
                    functionName: fn.name,
                    arguments: args.length 
                });
                throw error; // Re-throw for upstream handling
            }
        };
    }

    /**
     * Get recent errors
     * @param {number} limit - Number of recent errors to get
     * @param {string} type - Filter by error type
     * @returns {Array} Array of error objects
     */
    getRecentErrors(limit = 10, type = null) {
        try {
            if (!fs.existsSync(this.logFile)) {
                return [];
            }

            const logContent = fs.readFileSync(this.logFile, 'utf8');
            const lines = logContent.trim().split('\n').filter(line => line);
            
            let errors = lines.map(line => {
                try {
                    return JSON.parse(line);
                } catch (e) {
                    return null;
                }
            }).filter(error => error !== null);

            // Filter by type if specified
            if (type) {
                errors = errors.filter(error => error.type === type);
            }

            // Sort by timestamp (newest first) and limit
            return errors
                .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
                .slice(0, limit);
                
        } catch (error) {
            console.error('Failed to read error log:', error.message);
            return [];
        }
    }

    /**
     * Clear error logs
     * @returns {boolean} Success status
     */
    clearLogs() {
        try {
            if (fs.existsSync(this.logFile)) {
                fs.writeFileSync(this.logFile, '', 'utf8');
                console.log(' Error logs cleared');
                return true;
            }
            return true;
        } catch (error) {
            console.error('Failed to clear error logs:', error.message);
            return false;
        }
    }

    /**
     * Generate unique error ID
     * @private
     * @returns {string} Error ID
     */
    generateErrorId() {
        const timestamp = Date.now();
        const random = Math.random().toString(36).substring(2, 8);
        return `err_${timestamp}_${random}`;
    }

    /**
     * Ensure log directory exists
     * @private
     */
    ensureLogDirectory() {
        const logDir = path.dirname(this.logFile);
        if (!fs.existsSync(logDir)) {
            try {
                fs.mkdirSync(logDir, { recursive: true });
            } catch (error) {
                console.warn('Could not create log directory:', error.message);
            }
        }
    }

    /**
     * Get error handler status
     * @returns {Object} Status information
     */
    getStatus() {
        return {
            errorTypes: Object.values(this.errorTypes),
            logFile: this.logFile,
            debugMode: this.debugMode,
            logExists: fs.existsSync(this.logFile),
            ready: true
        };
    }

    /**
     * Set debug mode
     * @param {boolean} enabled - Enable debug mode
     */
    setDebugMode(enabled) {
        this.debugMode = enabled;
        console.log(` Debug mode: ${enabled ? 'enabled' : 'disabled'}`);
    }

    /**
     * Log error with type and metadata (for BaseStrategy compatibility)
     * @param {string} type - Error type
     * @param {Error|string} error - Error object or message
     * @param {Object} metadata - Additional metadata
     */
    logError(type, error, metadata = {}) {
        this.handle(error, type, null, metadata);
    }
}

// Export class (not singleton)
module.exports = ErrorHandler;