chahuadev-framework-en / modules /error-handler.js
chahuadev
Update README
857cdcf
/**
* 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;