energy-manager-iot
Version:
Library for energy management in IoT devices via MQTT protocol. Documentation: https://jonhvmp.github.io/energy-manager-iot-docs/
154 lines (153 loc) • 6.35 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EnergyManagerError = exports.ErrorSeverity = exports.ErrorType = void 0;
exports.createErrorHandler = createErrorHandler;
exports.handleError = handleError;
const logger_1 = __importDefault(require("./logger"));
/**
* Custom error types for the Energy Manager system
*/
var ErrorType;
(function (ErrorType) {
ErrorType["CONNECTION"] = "connection_error";
ErrorType["VALIDATION"] = "validation_error";
ErrorType["AUTHENTICATION"] = "authentication_error";
ErrorType["DEVICE_NOT_FOUND"] = "device_not_found";
ErrorType["GROUP_NOT_FOUND"] = "group_not_found";
ErrorType["COMMAND_FAILED"] = "command_failed";
ErrorType["CONFIGURATION_ERROR"] = "configuration_error";
ErrorType["TIMEOUT_ERROR"] = "timeout_error";
ErrorType["MESSAGE_FORMAT_ERROR"] = "message_format_error";
ErrorType["PROTOCOL_ERROR"] = "protocol_error";
ErrorType["PERMISSION_DENIED"] = "permission_denied";
ErrorType["RATE_LIMIT_EXCEEDED"] = "rate_limit_exceeded";
ErrorType["INTERNAL_ERROR"] = "internal_error";
})(ErrorType || (exports.ErrorType = ErrorType = {}));
/**
* Error severity levels
* Used to indicate the operational impact of an error
*/
var ErrorSeverity;
(function (ErrorSeverity) {
/** Critical errors requiring immediate attention */
ErrorSeverity["CRITICAL"] = "critical";
/** High-impact errors affecting system functionality */
ErrorSeverity["HIGH"] = "high";
/** Medium-impact errors affecting specific features */
ErrorSeverity["MEDIUM"] = "medium";
/** Low-impact errors with minimal functional impact */
ErrorSeverity["LOW"] = "low";
})(ErrorSeverity || (exports.ErrorSeverity = ErrorSeverity = {}));
/**
* Custom error class for Energy Manager errors
*
* Extends the standard Error class with additional properties
* for error type categorization and contextual data.
*/
class EnergyManagerError extends Error {
/** Classification of the error */
type;
/** Operational impact of the error */
severity;
/** Optional data related to the error context */
data;
/** Unique error code for lookup in documentation */
code;
/** Timestamp when the error occurred */
timestamp;
/** Optional correlation ID for tracing related operations */
correlationId;
/**
* Creates a new Energy Manager error
*
* @param message - Human-readable error message
* @param type - Error type classification
* @param data - Optional data or original error
* @param severity - Operational severity of the error (defaults to MEDIUM)
* @param correlationId - Optional correlation ID for tracing
*/
constructor(message, type, data, severity = ErrorSeverity.MEDIUM, correlationId) {
super(message);
this.name = 'EnergyManagerError';
this.type = type;
this.data = data;
this.severity = severity;
this.timestamp = new Date();
this.correlationId = correlationId;
// Generate error code based on type and timestamp
// Format: EM-{TYPE_PREFIX}-{TIMESTAMP}
const typePrefix = type.slice(0, 4).toUpperCase();
const timeCode = Math.floor(this.timestamp.getTime() / 1000).toString(36).slice(-6);
this.code = `EM-${typePrefix}-${timeCode}`;
// Correctly capture stack trace in TypeScript
Object.setPrototypeOf(this, EnergyManagerError.prototype);
}
/**
* Returns a structured object representation of the error
* for logging or serialization
*
* @returns Structured error object
*/
toJSON() {
return {
name: this.name,
message: this.message,
type: this.type,
severity: this.severity,
code: this.code,
timestamp: this.timestamp.toISOString(),
correlationId: this.correlationId,
data: this.data,
stack: this.stack
};
}
}
exports.EnergyManagerError = EnergyManagerError;
/**
* Creates a standardized error handler for a specific module
*
* @param moduleName - Name of the module using this error handler
* @returns An error handler function for the specified module
*/
function createErrorHandler(moduleName) {
const moduleLogger = logger_1.default.child(moduleName);
return function handleModuleError(error, context, correlationId) {
// Create logger with correlation ID if provided
const logger = correlationId ? moduleLogger.withCorrelationId(correlationId) : moduleLogger;
// If it's our custom error, log with additional information
if (error instanceof EnergyManagerError) {
logger.error(`[${error.type}]${context ? ` (${context})` : ''}: ${error.message}`, error.toJSON());
}
else {
// Convert standard errors to our format for consistent handling
const wrappedError = new EnergyManagerError(error.message, ErrorType.INTERNAL_ERROR, { originalStack: error.stack }, ErrorSeverity.MEDIUM, correlationId);
logger.error(`[UNEXPECTED_ERROR]${context ? ` (${context})` : ''}: ${error.message}`, wrappedError.toJSON());
}
throw error;
};
}
/**
* Handles errors in a consistent way across the library
*
* @param error - Error object to handle
* @param context - Optional context information for the error
* @param correlationId - Optional correlation ID for tracing
* @throws The original error after logging it
*
* @deprecated Use createErrorHandler() to create a module-specific error handler instead
*/
function handleError(error, context, correlationId) {
const logger = correlationId ? logger_1.default.withCorrelationId(correlationId) : logger_1.default;
// If it's our custom error, log with additional information
if (error instanceof EnergyManagerError) {
logger.error(`[${error.type}]${context ? ` (${context})` : ''}: ${error.message}`, error.toJSON());
}
else {
// For other errors
logger.error(`[UNEXPECTED_ERROR]${context ? ` (${context})` : ''}: ${error.message}`, { stack: error.stack });
}
throw error;
}