Error Handling System
Run ID: 69cae6cfc8ebe3066ba6f3d42026-03-30Development
PantheraHive BOS
BOS Dashboard

Error Handling System: Architecture Plan

Project: Error Handling System

Step: gemini → plan_architecture

Date: October 26, 2023


1. Introduction & Project Goals

This document outlines the comprehensive architecture plan for a robust and scalable Error Handling System. The system aims to centralize, standardize, and streamline the process of capturing, processing, analyzing, and acting upon errors generated across various applications and services within our ecosystem.

1.1. System Overview

The Error Handling System will serve as a single pane of glass for all operational errors, exceptions, and critical logs. It will provide developers and operations teams with real-time insights, actionable alerts, and historical data to quickly identify, diagnose, and resolve issues, thereby improving system reliability and user experience.

1.2. Key Objectives

1.3. Scope

This architecture plan covers the design of the core components required to achieve the stated objectives, from error generation to notification and analysis. It includes considerations for integration, scalability, security, and a phased implementation strategy.

2. Core Principles & Design Philosophies

The following principles will guide the design and implementation of the Error Handling System:

3. System Architecture Overview (Conceptual)

The Error Handling System will follow a layered, event-driven architecture.

text • 3,340 chars
+---------------------+     +---------------------+     +---------------------+
|                     |     |                     |     |                     |
|  Application A      |     |  Application B      |     |  Application C      |
|  (Frontend, Backend)|     |  (Microservice)     |     |  (Batch Job)        |
|                     |     |                     |     |                     |
+----------+----------+     +----------+----------+     +----------+----------+
           |                       |                       |
           | (Error Capture SDKs/Agents)                   |
           v                       v                       v
+----------+-----------------------+-----------------------+----------+
|                                                                     |
|            **1. Error Capture & Instrumentation Layer**             |
|                                                                     |
+----------+----------------------------------------------------------+
           |
           v
+----------+----------------------------------------------------------+
|                                                                     |
|            **2. Ingestion & Normalization Service**                |
|            (API Gateway, Message Queue, Processing Logic)            |
|                                                                     |
+----------+----------------------------------------------------------+
           |
           v
+----------+----------------------------------------------------------+
|                                                                     |
|            **3. Data Storage Layer**                               |
|            (Raw Error Storage, Processed Error Database)           |
|                                                                     |
+----------+----------+----------------------------------------------+
           |          |
           v          v
+----------+----------+----------------------------------------------+
|                     |                                              |
|            **4. Processing & Analysis Engine**                     |
|            (Error Grouping, Anomaly Detection, Enrichment)         |
|                     |                                              |
+----------+----------+----------------------------------------------+
           |          |
           v          v
+----------+----------+----------------------------------------------+
|                     |                                              |
|            **5. Alerting & Notification Service**                  |
|            (Rules Engine, Integrations: Slack, PagerDuty, Email)   |
|                     |                                              |
+----------+----------+----------------------------------------------+
           |
           v
+----------+----------------------------------------------------------+
|                                                                     |
|            **6. Reporting & Dashboarding Interface**               |
|            (Analytics, Visualization, Custom Dashboards)           |
|                                                                     |
+---------------------------------------------------------------------+
Sandboxed live preview

4. Detailed Component Breakdown

4.1. Error Capture & Instrumentation Layer

This layer is responsible for intercepting errors and exceptions at their source and transmitting them to the ingestion service.

  • Description: SDKs, libraries, or agents integrated directly into applications.
  • Responsibilities:

* Capture unhandled exceptions, specific error logs, and custom events.

* Collect contextual data (e.g., user ID, request payload, environment variables, device info, browser version).

* Sanitize sensitive data before transmission.

* Queue errors locally for resilience against temporary network issues.

  • Key Features:

* Language/framework-specific SDKs (e.g., Python, Java, Node.js, React, Android, iOS).

* Configuration options for sampling rates, data scrubbing, and environment tags.

* Asynchronous transmission to minimize impact on application performance.

  • Integration Points: Direct integration into application codebases.

4.2. Ingestion & Normalization Service

This service acts as the entry point for all incoming error data, validating and transforming it into a consistent format.

  • Description: A highly available, scalable API endpoint and message queue system.
  • Responsibilities:

* Receive raw error data from the capture layer via a secure API.

* Validate incoming data schema and apply rate limiting to prevent abuse or overload.

* Perform initial data normalization (e.g., timestamp standardization, common field renaming).

* Publish normalized error events to a message queue for asynchronous processing.

  • Key Features:

* API Gateway for secure access and authentication.

* Robust message queue (e.g., Kafka, AWS SQS/Kinesis, Azure Service Bus) for decoupling and buffering.

* Lightweight processing logic for schema validation and basic transformation.

  • Data Model for Normalized Errors (Example Fields):

* error_id (UUID)

* timestamp (ISO 8601)

* service_name

* environment (e.g., production, staging)

* level (e.g., error, warning, critical)

* message (short description)

* stack_trace

* type (e.g., SyntaxError, NetworkError)

* user_id (anonymized/hashed)

* request_url, request_method, request_body (scrubbed)

* release_version

* tags (e.g., frontend, backend, database)

* metadata (arbitrary key-value pairs)

4.3. Data Storage Layer

This layer is responsible for persisting raw and processed error data for real-time access and historical analysis.

  • Description: A combination of databases optimized for different access patterns.
  • Responsibilities:

* Store raw incoming error payloads (for debugging original format if needed).

* Store normalized, processed error events.

* Provide efficient querying capabilities for filtering, searching, and aggregation.

* Manage data retention policies.

  • Storage Options:

* Raw Error Storage: Object storage (e.g., AWS S3, Azure Blob Storage) for cost-effective long-term archival.

* Processed Error Database:

* NoSQL Document Database (e.g., MongoDB, DynamoDB, Cosmos DB): Flexible schema, good for storing complex JSON error objects, fast writes.

* Time-Series Database (e.g., InfluxDB, Prometheus, Elasticsearch/OpenSearch): Excellent for time-based queries, aggregations, and trend analysis. Elasticsearch is a strong candidate due to its search capabilities and scalability.

4.4. Processing & Analysis Engine

This engine consumes normalized error events, enriches them, and performs intelligent analysis.

  • Description: A set of microservices or serverless functions triggered by new error events from the message queue.
  • Responsibilities:

* Error Grouping: Identify similar errors (e.g., same stack trace, message pattern) to reduce noise and provide a single view for recurring issues.

* Enrichment: Add additional context from other systems (e.g., user details from a user service, deployment information).

* Rate Calculation: Track error frequency over time.

* Anomaly Detection: Identify sudden spikes in error rates or new error types.

* Root Cause Analysis (RCA) Support: Link errors to related logs, traces (if integrated with a distributed tracing system), and deployment events.

* State Management: Track the status of an error group (e.g., new, acknowledged, resolved, reopened).

  • Key Features:

* Scalable stream processing framework (e.g., Apache Flink, Spark Streaming, AWS Lambda with Kinesis/SQS triggers).

* Machine learning models for advanced grouping and anomaly detection (optional, in later phases).

4.5. Alerting & Notification Service

This service is responsible for evaluating processed errors against predefined rules and dispatching notifications.

  • Description: A rules engine that integrates with various communication channels.
  • Responsibilities:

* Define and manage alerting rules based on error attributes (e.g., severity, service, environment), frequency, and duration.

* Integrate with popular communication and incident management tools.

* Manage notification preferences (e.g., on-call rotations, escalation policies).

  • Key Features:

* Configurable alert conditions (e.g., "500 errors > 100/minute in production for Service X," "new critical error detected").

* Integration with:

* Chat Platforms: Slack, Microsoft Teams

* Incident Management: PagerDuty, Opsgenie, VictorOps

* Email: SMTP gateway

* SMS: Twilio, AWS SNS

* Deduplication and throttling of alerts to prevent notification storms.

4.6. Reporting & Dashboarding Interface

Provides a user interface for visualizing, exploring, and managing error data.

  • Description: A web-based application or integration with existing BI/monitoring tools.
  • Responsibilities:

* Display real-time error streams.

* Provide dashboards for key metrics (e.g., error rates by service, top errors, error trends).

* Offer search, filtering, and aggregation capabilities over historical error data.

* Allow users to view detailed error context, stack traces, and related events.

* Enable manual actions (e.g., mark as resolved, assign to a team, create a Jira ticket).

  • Key Metrics & Visualizations:

* Total Errors Over Time

*

gemini Output

Error Handling System - Code Generation & Implementation

This document provides a comprehensive, detailed, and professional output for the "Error Handling System" step of your workflow. It includes well-structured, production-ready Python code designed for robustness, maintainability, and extensibility, along with thorough explanations and integration guidelines.


1. Introduction: Building a Robust Error Handling System

A robust error handling system is crucial for any production application. It ensures that failures are gracefully managed, providing clear feedback to users, detailed diagnostics for developers, and maintaining application stability. This system aims to:

  • Centralize Error Logging: Streamline the logging of errors to various destinations (console, file, external services).
  • Define Custom Exceptions: Create application-specific exception types for better clarity and programmatic handling of business logic failures.
  • Standardize Error Responses: Ensure consistent and informative error messages for API consumers.
  • Isolate Error Handling Logic: Decouple error management from core business logic using decorators or middleware.
  • Enhance Debugging: Provide sufficient context and stack traces for quicker problem resolution.
  • Support Environment-Specific Behavior: Adjust logging levels and error reporting based on the deployment environment (e.g., development, production).

The following sections detail the components and provide the Python code implementation for such a system.

2. Core Components of the Error Handling System

Our error handling system will consist of several interconnected components:

  • config.py: Manages environment-specific settings for logging and error reporting.
  • exceptions.py: Defines custom application-specific exception classes that inherit from a base custom exception.
  • logger.py: Configures and provides a centralized logging utility, integrating with config.py.
  • error_handler.py: Implements decorators and conceptual middleware to catch and process exceptions, ensuring consistent logging and response formatting.
  • error_responses.py: A utility for creating standardized error payloads for API responses.
  • main.py (or app.py): Demonstrates the integration and usage of the error handling system within an example application context.

3. Code Implementation (Python)

Below is the production-ready Python code for each component.

3.1. config.py - Configuration Management

This file handles environment-specific settings.


# config.py

import os
from typing import Literal

class Config:
    """
    Base configuration class for the application.
    Manages environment-specific settings.
    """
    APP_NAME: str = os.getenv("APP_NAME", "MyApp")
    ENV: Literal["development", "testing", "production"] = os.getenv("FLASK_ENV", "development").lower() # Assuming Flask_ENV or similar
    DEBUG: bool = ENV == "development"

    # Logging settings
    LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO") if not DEBUG else "DEBUG"
    LOG_FILE_PATH: str = os.getenv("LOG_FILE_PATH", "application.log")
    LOG_MAX_BYTES: int = int(os.getenv("LOG_MAX_BYTES", 10 * 1024 * 1024)) # 10 MB
    LOG_BACKUP_COUNT: int = int(os.getenv("LOG_BACKUP_COUNT", 5))

    # Error Reporting Service (e.g., Sentry, Rollbar) - placeholder
    ERROR_REPORTING_ENABLED: bool = os.getenv("ERROR_REPORTING_ENABLED", "False").lower() == "true"
    ERROR_REPORTING_DSN: str = os.getenv("ERROR_REPORTING_DSN", "") # Data Source Name for Sentry/Rollbar

    # API Response settings
    API_DEFAULT_ERROR_MESSAGE: str = "An unexpected error occurred."
    API_SHOW_ERROR_DETAILS: bool = DEBUG # Only show full error details in development/debug mode

    @classmethod
    def get_log_level_int(cls) -> int:
        """Converts string log level to integer for logging module."""
        import logging
        return getattr(logging, cls.LOG_LEVEL.upper(), logging.INFO)

# You can create environment-specific configs if needed
class DevelopmentConfig(Config):
    DEBUG = True
    LOG_LEVEL = "DEBUG"
    API_SHOW_ERROR_DETAILS = True

class ProductionConfig(Config):
    DEBUG = False
    LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO") # Can be overridden by env var
    ERROR_REPORTING_ENABLED = True
    API_SHOW_ERROR_DETAILS = False

def get_config() -> type[Config]:
    """
    Returns the appropriate configuration class based on the environment.
    """
    env = os.getenv("FLASK_ENV", "development").lower()
    if env == "production":
        return ProductionConfig
    elif env == "development":
        return DevelopmentConfig
    else:
        return Config # Default or testing

# Initialize the active configuration
ACTIVE_CONFIG = get_config()

3.2. exceptions.py - Custom Exception Definitions

This file defines custom exceptions for application-specific errors.


# exceptions.py

from typing import Optional, Dict, Any

class ApplicationError(Exception):
    """
    Base exception for all application-specific errors.
    Provides a standardized structure for error messages and codes.
    """
    def __init__(self, message: str, error_code: Optional[str] = None, status_code: int = 500, details: Optional[Dict[str, Any]] = None):
        super().__init__(message)
        self.message = message
        self.error_code = error_code if error_code else self.__class__.__name__
        self.status_code = status_code
        self.details = details if details is not None else {}

    def to_dict(self) -> Dict[str, Any]:
        """Converts the exception details to a dictionary for API responses."""
        return {
            "error_code": self.error_code,
            "message": self.message,
            "details": self.details
        }

class BadRequestError(ApplicationError):
    """Exception for invalid client requests (e.g., validation errors)."""
    def __init__(self, message: str = "Bad Request", error_code: str = "BAD_REQUEST", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, error_code, 400, details)

class UnauthorizedError(ApplicationError):
    """Exception for authentication failures."""
    def __init__(self, message: str = "Unauthorized", error_code: str = "UNAUTHORIZED", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, error_code, 401, details)

class ForbiddenError(ApplicationError):
    """Exception for authorization failures."""
    def __init__(self, message: str = "Forbidden", error_code: str = "FORBIDDEN", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, error_code, 403, details)

class NotFoundError(ApplicationError):
    """Exception for resource not found."""
    def __init__(self, message: str = "Resource Not Found", error_code: str = "NOT_FOUND", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, error_code, 404, details)

class ConflictError(ApplicationError):
    """Exception for resource conflicts (e.g., duplicate entry)."""
    def __init__(self, message: str = "Conflict", error_code: str = "CONFLICT", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, error_code, 409, details)

class ServiceUnavailableError(ApplicationError):
    """Exception for when an external service is unavailable."""
    def __init__(self, message: str = "Service Unavailable", error_code: str = "SERVICE_UNAVAILABLE", details: Optional[Dict[str, Any]] = None):
        super().__init__(message, error_code, 503, details)

# Example of a more specific business logic error
class ProductNotFoundError(NotFoundError):
    """Specific error for when a product is not found."""
    def __init__(self, product_id: str):
        super().__init__(f"Product with ID '{product_id}' not found.", error_code="PRODUCT_NOT_FOUND", details={"product_id": product_id})

3.3. logger.py - Centralized Logging Utility

This file sets up a robust logging system using Python's logging module.


# logger.py

import logging
import os
from logging.handlers import RotatingFileHandler
from config import ACTIVE_CONFIG

class CustomLogger:
    """
    A singleton class to provide a centralized and configurable logging utility.
    """
    _instance = None
    _logger = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(CustomLogger, cls).__new__(cls)
            cls._instance._initialize_logger()
        return cls._instance

    def _initialize_logger(self):
        """Initializes the logger with console and file handlers."""
        if CustomLogger._logger is not None:
            return

        CustomLogger._logger = logging.getLogger(ACTIVE_CONFIG.APP_NAME)
        CustomLogger._logger.setLevel(ACTIVE_CONFIG.get_log_level_int())
        CustomLogger._logger.propagate = False # Prevent multiple logs if root logger is also configured

        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'
        )

        # Ensure handlers are not duplicated on re-initialization
        if not CustomLogger._logger.handlers:
            # Console handler
            console_handler = logging.StreamHandler()
            console_handler.setFormatter(formatter)
            CustomLogger._logger.addHandler(console_handler)

            # File handler (with rotation)
            log_dir = os.path.dirname(ACTIVE_CONFIG.LOG_FILE_PATH)
            if log_dir and not os.path.exists(log_dir):
                os.makedirs(log_dir)

            file_handler = RotatingFileHandler(
                ACTIVE_CONFIG.LOG_FILE_PATH,
                maxBytes=ACTIVE_CONFIG.LOG_MAX_BYTES,
                backupCount=ACTIVE_CONFIG.LOG_BACKUP_COUNT,
                encoding='utf-8'
            )
            file_handler.setFormatter(formatter)
            CustomLogger._logger.addHandler(file_handler)

            # Add more handlers here, e.g., for external logging services (Sentry, ELK)
            # if ACTIVE_CONFIG.ERROR_REPORTING_ENABLED and ACTIVE_CONFIG.ERROR_REPORTING_DSN:
            #     # Example: Sentry integration (requires 'sentry-sdk' package)
            #     import sentry_sdk
            #     from sentry_sdk.integrations.logging import LoggingIntegration
            #
            #     sentry_logging = LoggingIntegration(
            #         level=logging.INFO,        # Capture info and above as breadcrumbs
            #         event_level=logging.ERROR  # Send errors and above as events
            #     )
            #     sentry_sdk.init(
            #         dsn=ACTIVE_CONFIG.ERROR_REPORTING_DSN,
            #         integrations=[sentry_logging],
            #         environment=ACTIVE_CONFIG.ENV,
            #         traces_sample_rate=1.0 # Or a lower value in production
            #     )
            #     self.get_logger().info("Sentry initialized successfully.")

    def get_logger(self) -> logging.Logger:
        """Returns the configured logger instance."""
        return CustomLogger._logger

# Export the logger instance directly for easy import
logger = CustomLogger().get_logger()

3.4. error_responses.py - Standardized Error Response Formatter

This utility ensures consistent JSON error responses for APIs.


# error_responses.py

from typing import Dict, Any, Optional
from config import ACTIVE_CONFIG
from exceptions import ApplicationError

def create_error_response(
    exception: Exception,
    traceback_str: Optional[str] = None
) -> Dict[str, Any]:
    """
    Creates a standardized error response dictionary for API consumers.
    """
    status_code: int = 500
    error_code: str = "INTERNAL_SERVER_ERROR"
    message: str = ACTIVE_CONFIG.API_DEFAULT_ERROR_MESSAGE
    details: Dict[str, Any] = {}

    if isinstance(exception, ApplicationError):
        status_code = exception.status_code
        error_code = exception.error_code
        message = exception.message
        details = exception.details
    else:
        # For unexpected standard exceptions
        message = str(exception) if ACTIVE_CONFIG.API_SHOW_ERROR_DETAILS else ACTIVE_CONFIG.API_DEFAULT_ERROR_MESSAGE
        if ACTIVE_CONFIG.API_SHOW_ERROR_DETAILS:
            details["exception_type"] = type(exception).__name__

    response_payload = {
        "status": "error",
        "error": {
            "code": error_code,
            "message": message,
            "details": details
        }
    }

    if ACTIVE_CONFIG.API_SHOW_ERROR_DETAILS and traceback_str:
        response_payload["error"]["traceback"] = traceback_str

    return response_payload

3.5. error_handler.py - Error Handling Decorator and Middleware Concepts

This file contains a decorator for function-level error handling and outlines conceptual middleware for web frameworks.


# error_handler.py

import functools
import traceback
from typing import Callable, Any, TypeVar, Union
from logger import logger
from exceptions import ApplicationError
from error_responses import create_error_response
from config import ACTIVE_CONFIG

# Define a generic type for the decorated function's return value
R = TypeVar('R')

def handle_errors(
    default_status_code: int = 500,
    reraise_exceptions: bool = False
) -> Callable[[Callable[..., R]], Callable[..., Union[R, Dict[str, Any]]]]:
    """
    A decorator to gracefully handle exceptions in functions.
    It logs the error and returns a standardized error response (useful for API endpoints).

    Args:
        default_status_code (int): The HTTP status code to return for unhandled exceptions.
        reraise_exceptions
gemini Output

Error Handling System - Comprehensive Design & Implementation Plan

Date: October 26, 2023

Prepared For: [Customer Name/Organization]

Prepared By: PantheraHive


1. Executive Summary

This document outlines a comprehensive design and implementation plan for a robust Error Handling System tailored for your organization. A well-engineered error handling system is paramount for maintaining system stability, enhancing user experience, and optimizing operational efficiency. This plan details the core principles, key components, implementation strategy, and significant benefits of establishing such a system, ensuring proactive error detection, rapid resolution, and continuous improvement across your software ecosystem. By centralizing error insights and automating response mechanisms, we aim to transform reactive troubleshooting into a predictive and actionable process.

2. Introduction to the Error Handling System

An Error Handling System is a critical framework designed to systematically capture, log, monitor, alert, and manage errors and exceptions that occur within software applications and infrastructure. Its primary objectives are:

  • Improve System Reliability: Minimize downtime and ensure continuous service availability.
  • Enhance User Experience: Provide clear, helpful feedback to users and prevent disruptive system failures.
  • Accelerate Issue Resolution: Equip development and operations teams with timely, actionable data to diagnose and fix problems quickly.
  • Optimize Operational Efficiency: Reduce manual effort in debugging and incident management.
  • Provide Data-Driven Insights: Offer analytical capabilities to understand error trends, root causes, and system health over time.

This system moves beyond basic try-catch blocks to provide an integrated, enterprise-grade solution for managing the entire error lifecycle.

3. Core Principles and Design Philosophy

Our Error Handling System is built upon the following foundational principles:

  • Proactive Detection: Identify potential issues before they impact users or escalate into critical incidents.
  • Graceful Degradation: Ensure that system failures in one component do not cascade and bring down the entire application. Provide fallback mechanisms where possible.
  • Informative Logging: Capture detailed, contextual information about each error, including stack traces, request parameters, user context, and environmental variables.
  • Actionable Alerts: Deliver timely, prioritized notifications to the right teams, enabling swift response and minimizing Mean Time To Resolution (MTTR).
  • Automated Recovery/Retry: Implement intelligent retry mechanisms or automated self-healing processes for transient errors where appropriate.
  • User-Friendly Feedback: Present clear, non-technical error messages to end-users, guiding them on next steps without exposing sensitive system details.
  • Security & Privacy: Ensure that sensitive data is not logged or exposed during error handling, adhering to all relevant data protection regulations (e.g., GDPR, HIPAA).
  • Centralization & Unification: Consolidate error data from disparate services and applications into a single, unified platform for holistic visibility.

4. Key Components and Features

The proposed Error Handling System comprises several integrated components, each serving a distinct purpose in the error lifecycle:

4.1. Error Logging & Storage

  • Centralized Logging Infrastructure: A scalable, robust solution (e.g., ELK Stack, Grafana Loki, cloud-native logging services) to aggregate logs from all applications and services.
  • Structured Logging: Enforce a standardized, machine-readable format (e.g., JSON) for all error logs, including:

* timestamp: When the error occurred.

* error_id: Unique identifier for the error instance.

* severity: Critical, Error, Warning, Info, Debug.

* service_name: The application or microservice where the error originated.

* module/function: Specific code location.

* error_type: Categorization (e.g., DatabaseConnectionError, AuthenticationFailure).

* message: A human-readable description of the error.

* stack_trace: Detailed execution path.

* request_id: For tracing requests across multiple services.

* user_id / session_id: (Anonymized or hashed) for user context.

* context_data: Any relevant variables, input parameters, or environmental details.

  • Retention Policies: Configurable data retention based on log type and compliance requirements.

4.2. Error Monitoring & Alerting

  • Real-time Dashboards: Intuitive dashboards (e.g., Kibana, Grafana, Datadog) to visualize error trends, frequency, distribution, and impact.
  • Configurable Alert Rules: Define thresholds and patterns that trigger alerts:

* Rate-based: e.g., "More than 10 critical errors per minute."

* Unique error count: e.g., "A new, previously unseen error type appears."

* Specific error patterns: e.g., "Error message containing 'out of memory'."

* Impact-based: e.g., "Error rate for a specific user segment or API endpoint exceeds X%."

  • Multi-channel Notifications: Deliver alerts via preferred channels:

* Email, SMS

* Instant Messaging (Slack, Microsoft Teams)

* On-call management systems (PagerDuty, Opsgenie)

  • Dynamic Severity Escalation: Automatically escalate alerts based on severity, duration, or lack of acknowledgment.

4.3. Error Tracking & Management

  • Automatic Issue Creation: Integrate with incident management and ticketing systems (e.g., Jira, ServiceNow, GitHub Issues) to automatically create tickets for new or escalating errors.
  • Duplicate Error Grouping: Intelligently group similar errors to reduce noise and help teams focus on unique issues.
  • Status Tracking: Manage the lifecycle of an error from detection to resolution (New, Acknowledged, In Progress, Resolved, Ignored).
  • Root Cause Analysis (RCA) Support: Provide tools and processes to facilitate RCA, linking errors to deployments, code changes, and infrastructure events.
  • Historical Analysis: Access past error data for trend analysis and post-mortem reviews.

4.4. User Feedback & Experience

  • Customizable Error Pages/Messages: Display user-friendly error messages that provide guidance rather than technical jargon (e.g., "Something went wrong, please try again later" or "We are experiencing high traffic, your request will be processed shortly").
  • User Reporting Mechanism: Optionally provide a simple way for users to report issues directly from the application, automatically capturing relevant context.
  • Graceful Fallbacks: Implement strategies to ensure core application functionality remains available even when non-critical components fail.

4.5. Reporting & Analytics

  • Error Trend Reports: Analyze error frequency, distribution by service, module, or error type over time.
  • Mean Time To Resolution (MTTR) Tracking: Measure and improve the efficiency of error resolution.
  • Impact Analysis Reports: Understand the business impact of errors (e.g., affected users, lost transactions).
  • Service Level Objective (SLO) Monitoring: Track error rates against defined SLOs and trigger alerts when thresholds are breached.

5. Implementation Strategy and Phased Rollout

Implementing a comprehensive Error Handling System is a strategic initiative best approached in phases to ensure minimal disruption and maximum value realization.

  • Phase 1: Foundation & Core Logging (Weeks 1-4)

* Objective: Establish the centralized logging infrastructure and integrate critical applications for basic error capture.

* Activities:

* Provision and configure the chosen logging platform (e.g., ELK Stack, cloud logging).

* Define a standardized structured logging format.

* Integrate initial set of high-priority applications/services with the logging system.

* Develop basic dashboards for raw log visualization.

* Deliverables: Centralized log repository, initial application integrations, raw log dashboards.

  • Phase 2: Monitoring & Alerting (Weeks 5-8)

* Objective: Implement real-time monitoring and establish critical alerting mechanisms.

* Activities:

* Design and build monitoring dashboards for key error metrics (e.g., error rates, unique error types).

* Define initial alert rules and thresholds for critical system errors.

* Integrate with notification channels (Slack, email, PagerDuty).

* Establish on-call rotations and escalation policies.

* Deliverables: Monitoring dashboards, configured critical alerts, notification integrations, documented on-call procedures.

  • Phase 3: Advanced Features & Integration (Weeks 9-12)

* Objective: Integrate with incident management, enhance user feedback, and develop advanced analytics.

* Activities:

* Integrate with the existing ticketing/incident management system (e.g., Jira) for automatic issue creation.

* Implement intelligent error grouping and duplicate detection.

* Refine user-facing error messages and implement graceful degradation strategies.

* Develop comprehensive reporting and analytics capabilities.

* Deliverables: Automated incident creation, refined user experience, detailed error reports.

  • Phase 4: Continuous Improvement & Expansion (Ongoing)

* Objective: Continuously refine the system, expand coverage, and leverage insights for proactive system hardening.

* Activities:

* Regularly review error patterns and adjust alert thresholds and rules.

* Expand integration to all remaining applications and services.

* Conduct training for development and operations teams on system usage.

* Utilize error data for proactive code refactoring, system improvements, and identifying technical debt.

* Deliverables: System-wide coverage, optimized alert configurations, improved MTTR, reduced error rates.

6. Benefits of a Robust Error Handling System

Implementing this comprehensive Error Handling System will yield significant benefits across your organization:

  • Improved System Stability & Reliability: Proactive identification and faster resolution of issues lead to fewer outages and more reliable services.
  • Enhanced User Experience: Minimizes user frustration by providing clear feedback and maintaining application availability even during minor incidents.
  • Increased Operational Efficiency: Automates much of the manual effort in identifying, triaging, and tracking errors, freeing up engineering resources.
  • Faster Time to Resolution (MTTR): Engineers receive immediate, contextualized information, drastically reducing the time needed to diagnose and fix problems.
  • Reduced Development Costs: Identifying and resolving bugs earlier in the development lifecycle is significantly less expensive than fixing them in production.
  • Data-Driven Decision Making: Provides valuable insights into system health, common failure points, and areas for architectural improvement.
  • Better Compliance & Auditability: Creates a clear, auditable record of system incidents and responses, aiding in regulatory compliance.
  • Empowered Teams: Gives development and operations teams the tools and information they need to confidently manage and improve system quality.

7. Recommended Technologies/Tools (Examples)

While the specific technology stack will be tailored to your existing infrastructure and preferences, here are examples of robust tools commonly used for each component:

  • Logging & Storage:

* Open Source: ELK Stack (Elasticsearch, Logstash, Kibana), Grafana Loki.

* Commercial/Cloud-Native: Splunk, Datadog Logs, AWS CloudWatch Logs, Google Cloud Logging, Azure Monitor.

  • Monitoring & Alerting:

* Open Source: Prometheus + Grafana.

* Commercial/SaaS: Sentry, Rollbar, Datadog, New Relic, AppDynamics.

  • Incident Management & On-Call:

* PagerDuty, Opsgenie, VictorOps.

  • Ticketing Systems:

* Jira, ServiceNow, GitHub Issues, GitLab Issues.

PantheraHive will work with your team to select and integrate the most suitable technologies that align with your current ecosystem and future goals.

8. Next Steps & Call to Action

To move forward with establishing your robust Error Handling System, we recommend the following immediate actions:

  1. Schedule a Follow-up Workshop: A dedicated session to delve deeper into your specific application architecture, current error handling practices, and detailed requirements.
  2. Current System Audit: PantheraHive will conduct an initial audit of your existing infrastructure and applications to identify key integration points and potential challenges.
  3. **Define Key Performance Indicators (KPIs):
error_handling_system.txt
Download source file
Copy all content
Full output as text
Download ZIP
IDE-ready project ZIP
Copy share link
Permanent URL for this run
Get Embed Code
Embed this result on any website
Print / Save PDF
Use browser print dialog
\n\n\n"); var hasSrcMain=Object.keys(extracted).some(function(k){return k.indexOf("src/main")>=0;}); if(!hasSrcMain) zip.file(folder+"src/main."+ext,"import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\nimport './index.css'\n\nReactDOM.createRoot(document.getElementById('root')!).render(\n \n \n \n)\n"); var hasSrcApp=Object.keys(extracted).some(function(k){return k==="src/App."+ext||k==="App."+ext;}); if(!hasSrcApp) zip.file(folder+"src/App."+ext,"import React from 'react'\nimport './App.css'\n\nfunction App(){\n return(\n
\n
\n

"+slugTitle(pn)+"

\n

Built with PantheraHive BOS

\n
\n
\n )\n}\nexport default App\n"); zip.file(folder+"src/index.css","*{margin:0;padding:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;background:#f0f2f5;color:#1a1a2e}\n.app{min-height:100vh;display:flex;flex-direction:column}\n.app-header{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:40px}\nh1{font-size:2.5rem;font-weight:700}\n"); zip.file(folder+"src/App.css",""); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/pages/.gitkeep",""); zip.file(folder+"src/hooks/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nnpm run dev\n\`\`\`\n\n## Build\n\`\`\`bash\nnpm run build\n\`\`\`\n\n## Open in IDE\nOpen the project folder in VS Code or WebStorm.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n"); } /* --- Vue (Vite + Composition API + TypeScript) --- */ function buildVue(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{\n "name": "'+pn+'",\n "version": "0.0.0",\n "type": "module",\n "scripts": {\n "dev": "vite",\n "build": "vue-tsc -b && vite build",\n "preview": "vite preview"\n },\n "dependencies": {\n "vue": "^3.5.13",\n "vue-router": "^4.4.5",\n "pinia": "^2.3.0",\n "axios": "^1.7.9"\n },\n "devDependencies": {\n "@vitejs/plugin-vue": "^5.2.1",\n "typescript": "~5.7.3",\n "vite": "^6.0.5",\n "vue-tsc": "^2.2.0"\n }\n}\n'); zip.file(folder+"vite.config.ts","import { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport { resolve } from 'path'\n\nexport default defineConfig({\n plugins: [vue()],\n resolve: { alias: { '@': resolve(__dirname,'src') } }\n})\n"); zip.file(folder+"tsconfig.json",'{"files":[],"references":[{"path":"./tsconfig.app.json"},{"path":"./tsconfig.node.json"}]}\n'); zip.file(folder+"tsconfig.app.json",'{\n "compilerOptions":{\n "target":"ES2020","useDefineForClassFields":true,"module":"ESNext","lib":["ES2020","DOM","DOM.Iterable"],\n "skipLibCheck":true,"moduleResolution":"bundler","allowImportingTsExtensions":true,\n "isolatedModules":true,"moduleDetection":"force","noEmit":true,"jsxImportSource":"vue",\n "strict":true,"paths":{"@/*":["./src/*"]}\n },\n "include":["src/**/*.ts","src/**/*.d.ts","src/**/*.tsx","src/**/*.vue"]\n}\n'); zip.file(folder+"env.d.ts","/// \n"); zip.file(folder+"index.html","\n\n\n \n \n "+slugTitle(pn)+"\n\n\n
\n \n\n\n"); var hasMain=Object.keys(extracted).some(function(k){return k==="src/main.ts"||k==="main.ts";}); if(!hasMain) zip.file(folder+"src/main.ts","import { createApp } from 'vue'\nimport { createPinia } from 'pinia'\nimport App from './App.vue'\nimport './assets/main.css'\n\nconst app = createApp(App)\napp.use(createPinia())\napp.mount('#app')\n"); var hasApp=Object.keys(extracted).some(function(k){return k.indexOf("App.vue")>=0;}); if(!hasApp) zip.file(folder+"src/App.vue","\n\n\n\n\n"); zip.file(folder+"src/assets/main.css","*{margin:0;padding:0;box-sizing:border-box}body{font-family:system-ui,sans-serif;background:#fff;color:#213547}\n"); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/views/.gitkeep",""); zip.file(folder+"src/stores/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nnpm run dev\n\`\`\`\n\n## Build\n\`\`\`bash\nnpm run build\n\`\`\`\n\nOpen in VS Code or WebStorm.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n"); } /* --- Angular (v19 standalone) --- */ function buildAngular(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var sel=pn.replace(/_/g,"-"); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{\n "name": "'+pn+'",\n "version": "0.0.0",\n "scripts": {\n "ng": "ng",\n "start": "ng serve",\n "build": "ng build",\n "test": "ng test"\n },\n "dependencies": {\n "@angular/animations": "^19.0.0",\n "@angular/common": "^19.0.0",\n "@angular/compiler": "^19.0.0",\n "@angular/core": "^19.0.0",\n "@angular/forms": "^19.0.0",\n "@angular/platform-browser": "^19.0.0",\n "@angular/platform-browser-dynamic": "^19.0.0",\n "@angular/router": "^19.0.0",\n "rxjs": "~7.8.0",\n "tslib": "^2.3.0",\n "zone.js": "~0.15.0"\n },\n "devDependencies": {\n "@angular-devkit/build-angular": "^19.0.0",\n "@angular/cli": "^19.0.0",\n "@angular/compiler-cli": "^19.0.0",\n "typescript": "~5.6.0"\n }\n}\n'); zip.file(folder+"angular.json",'{\n "$schema": "./node_modules/@angular/cli/lib/config/schema.json",\n "version": 1,\n "newProjectRoot": "projects",\n "projects": {\n "'+pn+'": {\n "projectType": "application",\n "root": "",\n "sourceRoot": "src",\n "prefix": "app",\n "architect": {\n "build": {\n "builder": "@angular-devkit/build-angular:application",\n "options": {\n "outputPath": "dist/'+pn+'",\n "index": "src/index.html",\n "browser": "src/main.ts",\n "tsConfig": "tsconfig.app.json",\n "styles": ["src/styles.css"],\n "scripts": []\n }\n },\n "serve": {"builder":"@angular-devkit/build-angular:dev-server","configurations":{"production":{"buildTarget":"'+pn+':build:production"},"development":{"buildTarget":"'+pn+':build:development"}},"defaultConfiguration":"development"}\n }\n }\n }\n}\n'); zip.file(folder+"tsconfig.json",'{\n "compileOnSave": false,\n "compilerOptions": {"baseUrl":"./","outDir":"./dist/out-tsc","forceConsistentCasingInFileNames":true,"strict":true,"noImplicitOverride":true,"noPropertyAccessFromIndexSignature":true,"noImplicitReturns":true,"noFallthroughCasesInSwitch":true,"paths":{"@/*":["src/*"]},"skipLibCheck":true,"esModuleInterop":true,"sourceMap":true,"declaration":false,"experimentalDecorators":true,"moduleResolution":"bundler","importHelpers":true,"target":"ES2022","module":"ES2022","useDefineForClassFields":false,"lib":["ES2022","dom"]},\n "references":[{"path":"./tsconfig.app.json"}]\n}\n'); zip.file(folder+"tsconfig.app.json",'{\n "extends":"./tsconfig.json",\n "compilerOptions":{"outDir":"./dist/out-tsc","types":[]},\n "files":["src/main.ts"],\n "include":["src/**/*.d.ts"]\n}\n'); zip.file(folder+"src/index.html","\n\n\n \n "+slugTitle(pn)+"\n \n \n \n\n\n \n\n\n"); zip.file(folder+"src/main.ts","import { bootstrapApplication } from '@angular/platform-browser';\nimport { appConfig } from './app/app.config';\nimport { AppComponent } from './app/app.component';\n\nbootstrapApplication(AppComponent, appConfig)\n .catch(err => console.error(err));\n"); zip.file(folder+"src/styles.css","* { margin: 0; padding: 0; box-sizing: border-box; }\nbody { font-family: system-ui, -apple-system, sans-serif; background: #f9fafb; color: #111827; }\n"); var hasComp=Object.keys(extracted).some(function(k){return k.indexOf("app.component")>=0;}); if(!hasComp){ zip.file(folder+"src/app/app.component.ts","import { Component } from '@angular/core';\nimport { RouterOutlet } from '@angular/router';\n\n@Component({\n selector: 'app-root',\n standalone: true,\n imports: [RouterOutlet],\n templateUrl: './app.component.html',\n styleUrl: './app.component.css'\n})\nexport class AppComponent {\n title = '"+pn+"';\n}\n"); zip.file(folder+"src/app/app.component.html","
\n
\n

"+slugTitle(pn)+"

\n

Built with PantheraHive BOS

\n
\n \n
\n"); zip.file(folder+"src/app/app.component.css",".app-header{display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:60vh;gap:16px}h1{font-size:2.5rem;font-weight:700;color:#6366f1}\n"); } zip.file(folder+"src/app/app.config.ts","import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';\nimport { provideRouter } from '@angular/router';\nimport { routes } from './app.routes';\n\nexport const appConfig: ApplicationConfig = {\n providers: [\n provideZoneChangeDetection({ eventCoalescing: true }),\n provideRouter(routes)\n ]\n};\n"); zip.file(folder+"src/app/app.routes.ts","import { Routes } from '@angular/router';\n\nexport const routes: Routes = [];\n"); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nng serve\n# or: npm start\n\`\`\`\n\n## Build\n\`\`\`bash\nng build\n\`\`\`\n\nOpen in VS Code with Angular Language Service extension.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n.angular/\n"); } /* --- Python --- */ function buildPython(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^\`\`\`[\w]*\n?/m,"").replace(/\n?\`\`\`$/m,"").trim(); var reqMap={"numpy":"numpy","pandas":"pandas","sklearn":"scikit-learn","tensorflow":"tensorflow","torch":"torch","flask":"flask","fastapi":"fastapi","uvicorn":"uvicorn","requests":"requests","sqlalchemy":"sqlalchemy","pydantic":"pydantic","dotenv":"python-dotenv","PIL":"Pillow","cv2":"opencv-python","matplotlib":"matplotlib","seaborn":"seaborn","scipy":"scipy"}; var reqs=[]; Object.keys(reqMap).forEach(function(k){if(src.indexOf("import "+k)>=0||src.indexOf("from "+k)>=0)reqs.push(reqMap[k]);}); var reqsTxt=reqs.length?reqs.join("\n"):"# add dependencies here\n"; zip.file(folder+"main.py",src||"# "+title+"\n# Generated by PantheraHive BOS\n\nprint(title+\" loaded\")\n"); zip.file(folder+"requirements.txt",reqsTxt); zip.file(folder+".env.example","# Environment variables\n"); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\npython3 -m venv .venv\nsource .venv/bin/activate\npip install -r requirements.txt\n\`\`\`\n\n## Run\n\`\`\`bash\npython main.py\n\`\`\`\n"); zip.file(folder+".gitignore",".venv/\n__pycache__/\n*.pyc\n.env\n.DS_Store\n"); } /* --- Node.js --- */ function buildNode(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^\`\`\`[\w]*\n?/m,"").replace(/\n?\`\`\`$/m,"").trim(); var depMap={"mongoose":"^8.0.0","dotenv":"^16.4.5","axios":"^1.7.9","cors":"^2.8.5","bcryptjs":"^2.4.3","jsonwebtoken":"^9.0.2","socket.io":"^4.7.4","uuid":"^9.0.1","zod":"^3.22.4","express":"^4.18.2"}; var deps={}; Object.keys(depMap).forEach(function(k){if(src.indexOf(k)>=0)deps[k]=depMap[k];}); if(!deps["express"])deps["express"]="^4.18.2"; var pkgJson=JSON.stringify({"name":pn,"version":"1.0.0","main":"src/index.js","scripts":{"start":"node src/index.js","dev":"nodemon src/index.js"},"dependencies":deps,"devDependencies":{"nodemon":"^3.0.3"}},null,2)+"\n"; zip.file(folder+"package.json",pkgJson); var fallback="const express=require(\"express\");\nconst app=express();\napp.use(express.json());\n\napp.get(\"/\",(req,res)=>{\n res.json({message:\""+title+" API\"});\n});\n\nconst PORT=process.env.PORT||3000;\napp.listen(PORT,()=>console.log(\"Server on port \"+PORT));\n"; zip.file(folder+"src/index.js",src||fallback); zip.file(folder+".env.example","PORT=3000\n"); zip.file(folder+".gitignore","node_modules/\n.env\n.DS_Store\n"); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\n\`\`\`\n\n## Run\n\`\`\`bash\nnpm run dev\n\`\`\`\n"); } /* --- Vanilla HTML --- */ function buildVanillaHtml(zip,folder,app,code){ var title=slugTitle(app); var isFullDoc=code.trim().toLowerCase().indexOf("=0||code.trim().toLowerCase().indexOf("=0; var indexHtml=isFullDoc?code:"\n\n\n\n\n"+title+"\n\n\n\n"+code+"\n\n\n\n"; zip.file(folder+"index.html",indexHtml); zip.file(folder+"style.css","/* "+title+" — styles */\n*{margin:0;padding:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;background:#fff;color:#1a1a2e}\n"); zip.file(folder+"script.js","/* "+title+" — scripts */\n"); zip.file(folder+"assets/.gitkeep",""); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Open\nDouble-click \`index.html\` in your browser.\n\nOr serve locally:\n\`\`\`bash\nnpx serve .\n# or\npython3 -m http.server 3000\n\`\`\`\n"); zip.file(folder+".gitignore",".DS_Store\nnode_modules/\n.env\n"); } /* ===== MAIN ===== */ var sc=document.createElement("script"); sc.src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"; sc.onerror=function(){ if(lbl)lbl.textContent="Download ZIP"; alert("JSZip load failed — check connection."); }; sc.onload=function(){ var zip=new JSZip(); var base=(_phFname||"output").replace(/\.[^.]+$/,""); var app=base.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"my_app"; var folder=app+"/"; var vc=document.getElementById("panel-content"); var panelTxt=vc?(vc.innerText||vc.textContent||""):""; var lang=detectLang(_phCode,panelTxt); if(_phIsHtml){ buildVanillaHtml(zip,folder,app,_phCode); } else if(lang==="flutter"){ buildFlutter(zip,folder,app,_phCode,panelTxt); } else if(lang==="react-native"){ buildReactNative(zip,folder,app,_phCode,panelTxt); } else if(lang==="swift"){ buildSwift(zip,folder,app,_phCode,panelTxt); } else if(lang==="kotlin"){ buildKotlin(zip,folder,app,_phCode,panelTxt); } else if(lang==="react"){ buildReact(zip,folder,app,_phCode,panelTxt); } else if(lang==="vue"){ buildVue(zip,folder,app,_phCode,panelTxt); } else if(lang==="angular"){ buildAngular(zip,folder,app,_phCode,panelTxt); } else if(lang==="python"){ buildPython(zip,folder,app,_phCode); } else if(lang==="node"){ buildNode(zip,folder,app,_phCode); } else { /* Document/content workflow */ var title=app.replace(/_/g," "); var md=_phAll||_phCode||panelTxt||"No content"; zip.file(folder+app+".md",md); var h=""+title+""; h+="

"+title+"

"; var hc=md.replace(/&/g,"&").replace(//g,">"); hc=hc.replace(/^### (.+)$/gm,"

$1

"); hc=hc.replace(/^## (.+)$/gm,"

$1

"); hc=hc.replace(/^# (.+)$/gm,"

$1

"); hc=hc.replace(/\*\*(.+?)\*\*/g,"$1"); hc=hc.replace(/\n{2,}/g,"

"); h+="

"+hc+"

Generated by PantheraHive BOS
"; zip.file(folder+app+".html",h); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\nFiles:\n- "+app+".md (Markdown)\n- "+app+".html (styled HTML)\n"); } zip.generateAsync({type:"blob"}).then(function(blob){ var a=document.createElement("a"); a.href=URL.createObjectURL(blob); a.download=app+".zip"; a.click(); URL.revokeObjectURL(a.href); if(lbl)lbl.textContent="Download ZIP"; }); }; document.head.appendChild(sc); } function phShare(){navigator.clipboard.writeText(window.location.href).then(function(){var el=document.getElementById("ph-share-lbl");if(el){el.textContent="Link copied!";setTimeout(function(){el.textContent="Copy share link";},2500);}});}function phEmbed(){var runId=window.location.pathname.split("/").pop().replace(".html","");var embedUrl="https://pantherahive.com/embed/"+runId;var code='';navigator.clipboard.writeText(code).then(function(){var el=document.getElementById("ph-embed-lbl");if(el){el.textContent="Embed code copied!";setTimeout(function(){el.textContent="Get Embed Code";},2500);}});}