/** * The ErrorHandler class implements the Singleton pattern for error handling and logging. * Provides methods for creating a single instance and handling errors with context. * * Usage example: * ```js * try { * // Code that may throw an error * } catch (error) { * const errorHandler = ErrorHandler.getInstance(); * const message = errorHandler.wrapError(error, "Creating new merchant"); * ui.notifications.error(message); * } * ``` */ export class ErrorHandler { static #instance = null; // Private static field for storing the single instance /** * Class constructor. Implements the Singleton pattern. * If an instance already exists, returns it. * Otherwise creates a new instance. */ constructor() { if (ErrorHandler.#instance) { return ErrorHandler.#instance; } ErrorHandler.#instance = this; } /** * Static method to get the class instance. * If the instance doesn't exist, creates a new one. * @returns {ErrorHandler} The single instance of ErrorHandler class */ static getInstance() { if (!ErrorHandler.#instance) { ErrorHandler.#instance = new ErrorHandler(); } return ErrorHandler.#instance; } /** * Method for handling errors with added context. * Forms a detailed error message with version information and call stack. * @param {Error} error - Error object * @param {string} context - Context in which the error occurred * @returns {string} Formatted error message */ wrapError(error, context) { const moduleInfo = game.modules.get('test_tube_merchant'); const systemInfo = game.system; const errorMessage = ` Торговец из пробирки / Test Tube Merchant Версия Foundry: ${game.version} Версия системы: ${systemInfo.version} Версия модуля: ${moduleInfo.version} Контекст ошибки: ${context} Ошибка: ${error.message} Стек вызовов: ${error.stack} Пожалуйста, отправьте эту информацию на Discord: https://discord.gg/CwxwDHZAGy `; console.error(errorMessage); return errorMessage; } }