Error Handling System
Run ID: 69cd20783e7fb09ff16a82982026-04-01Development
PantheraHive BOS
BOS Dashboard

Error Handling System: Architecture Plan

Project Step: gemini → plan_architecture

Date: October 26, 2023

Prepared For: Customer Deliverable


1. Executive Summary

This document outlines a comprehensive architectural plan for a robust and scalable Error Handling System. The primary goal of this system is to centralize, standardize, and streamline the detection, capture, logging, notification, and resolution of errors across all applications and services within our ecosystem. A well-designed error handling system is critical for maintaining application stability, improving user experience, reducing downtime, and enabling proactive issue resolution. This plan details the core components, their interactions, key design principles, and technology considerations to build a resilient and efficient error management solution.

2. Core Principles & Goals

The architecture of the Error Handling System will be guided by the following principles and aims to achieve these goals:

3. System Architecture Overview

The Error Handling System will be structured into several interconnected components, each responsible for a specific stage of the error lifecycle.

3.1. High-Level Architectural Diagram (Conceptual Flow)

text • 1,684 chars
+-------------------+     +---------------------+     +------------------+     +-------------------+
|                   |     |                     |     |                  |     |                   |
| 1. Application(s) |     | 2. Error Ingestion  |     | 3. Error Storage |     | 4. Error Processing |
|   - SDKs          |     |   - API Gateway     |     |   - Database     |     |   - Enrichment    |
|   - Log Adapters  +----->   - Message Queue   +----->   - Log Store    +----->   - Deduplication |
|   - Custom Agents |     |                     |     |                  |     |   - Alerting      |
|                   |     |                     |     |                  |     |   - Reporting     |
+-------------------+     +---------------------+     +------------------+     +-------------------+
                                                                                     |
                                                                                     v
+-------------------+     +-------------------+     +-------------------+     +-------------------+
|                   |     |                   |     |                   |     |                   |
| 5. Notification   |     | 6. Dashboards &   |     | 7. Resolution     |     | 8. Configuration  |
|   - Email         |     |    Reporting      |     |   - Ticketing     |     |   - Rules Engine  |
|   - SMS           +----->   - Analytics     |     |   - Collaboration |     |   - Integrations  |
|   - PagerDuty     |     |   - Trends        |     |                   |     |                   |
+-------------------+     +-------------------+     +-------------------+     +-------------------+
Sandboxed live preview

3.2. Detailed Component Breakdown

##### 3.2.1. Error Capture & Ingestion

  • Purpose: The entry point for all errors generated by applications.
  • Mechanism:

* Client SDKs/Libraries: Language-specific libraries (e.g., for Python, Java, Node.js, .NET) that intercept exceptions, log messages, and gather contextual information (e.g., stack traces, request data, user info, environment variables).

* Log Adapters: For applications that primarily log to standard outputs or files, adapters will forward these logs to the ingestion layer.

* API Gateway: A dedicated, highly available endpoint to receive error payloads via HTTP/HTTPS. This acts as a buffer and validator.

* Message Queue: A robust, asynchronous message queue (e.g., Kafka, RabbitMQ, AWS SQS) will decouple error producers from consumers, ensuring high throughput and resilience against backpressure. Errors are published to specific topics/queues.

  • Data Format: Standardized JSON payload for error events, including fields like:

* timestamp

* application_name

* environment (dev, staging, prod)

* host_id / service_instance_id

* error_type (e.g., ValueError, NullPointerException)

* message

* stack_trace

* severity (e.g., DEBUG, INFO, WARN, ERROR, CRITICAL)

* user_id (if applicable)

* request_context (HTTP method, URL, headers, body snippet)

* custom_tags / metadata

##### 3.2.2. Error Enrichment & Processing

  • Purpose: To add valuable context, normalize data, and prepare errors for storage and analysis.
  • Mechanism:

* Stream Processing Engine: A real-time stream processing framework (e.g., Apache Flink, Kafka Streams, AWS Kinesis Analytics) consumes messages from the ingestion queue.

* Enrichment Services:

* Context Lookup: Add metadata from internal services (e.g., service ownership, team contacts, deployment versions) based on application_name or host_id.

* Geo-IP Lookup: For client-side errors, enrich with geographical information.

* User Information: Anonymized or hashed user data from internal user services.

* Deduplication & Grouping:

* Fingerprinting: Generate a unique hash for similar errors (e.g., based on error type, message, and cleaned stack trace) to group identical issues.

* Rate Limiting: Suppress repeated identical errors within a short timeframe to prevent alert storms.

* Error Aggregation: Combine occurrences of the same error into a single logical "issue" with a count.

* Data Validation & Transformation: Ensure data adheres to schema and transform as necessary.

##### 3.2.3. Error Storage & Persistence

  • Purpose: To durably store raw error events and processed error issues for analysis, historical tracking, and auditing.
  • Mechanism:

* Raw Error Store (High-Volume, Time-Series):

* Technology: Distributed log store (e.g., Elasticsearch, Loki, Splunk) optimized for ingestion and full-text search.

* Retention: Configurable retention policies (e.g., 30-90 days for raw data).

* Processed Error Store (Relational/NoSQL for Issues):

* Technology: A database suitable for structured data (e.g., PostgreSQL, MongoDB, DynamoDB). Stores aggregated error issues, their status, assignment, and resolution history.

* Retention: Longer retention (e.g., 1-2 years) for aggregated issue data.

* Archival Storage: For long-term, low-cost storage of historical raw data that is rarely accessed (e.g., AWS S3, Google Cloud Storage).

##### 3.2.4. Notification & Alerting

  • Purpose: To proactively inform relevant teams and individuals about new or recurring critical errors.
  • Mechanism:

* Alerting Engine: A rules-based engine that evaluates processed error streams against predefined conditions.

* Notification Channels:

* Email: For general team notifications.

* SMS/Push Notifications: For critical, high-severity alerts (e.g., via PagerDuty, Opsgenie, VictorOps integration).

* Chat Platforms: Integration with Slack, Microsoft Teams for team visibility and discussion.

* Webhooks: Generic integration for custom systems.

* Configurable Rules: Allow teams to define their own alert thresholds, severities, and recipient lists based on error attributes (e.g., application, environment, error type, frequency).

* Escalation Policies: Define escalation paths for unacknowledged critical alerts.

##### 3.2.5. Dashboards & Reporting

  • Purpose: To provide visibility into error trends, system health, and facilitate root cause analysis.
  • Mechanism:

* Visualization Tool: (e.g., Kibana for Elasticsearch, Grafana, custom UI) connected to the error stores.

* Key Metrics & Dashboards:

* Error Rate: Errors per minute/hour/day.

* Top N Errors: Most frequent error types.

* New Errors: Recently introduced error patterns.

* Error by Application/Service: Distribution of errors across the system.

* Error by Environment/Severity: Breakdown of issues.

* Error Resolution Time: Track mean time to resolution (MTTR).

* Impact Analysis: Correlation with deployment events or user activity.

* Search & Filtering: Powerful search capabilities across all error attributes.

* Historical Trends: Analyze error patterns over time.

##### 3.2.6. Error Resolution & Workflow Integration

  • Purpose: To integrate error management with existing incident response and development workflows.
  • Mechanism:

* Ticketing System Integration: Automatic creation of tickets (e.g., Jira, ServiceNow) for new critical error issues, pre-filled with relevant context.

* Collaboration Tools: Links to error details within chat messages, facilitating discussion.

* Status Management: Ability to mark errors as New, Acknowledged, In Progress, Resolved, Ignored, Archived.

* Assignment: Assign error issues to specific teams or individuals.

* Resolution Tracking: Record resolution steps and links to code changes or deployments.

##### 3.2.7. Configuration & Management

  • Purpose: To provide a central interface for managing system settings, rules, and integrations.
  • Mechanism:

* Admin UI: A web-based interface for configuration.

* Rule Engine: Define and manage alerting rules, deduplication logic, and data enrichment policies.

* User & Role Management: Control access to different parts of the system.

* Integration Settings: Manage API keys, webhooks, and connection details for external services.

4. Technology Stack Considerations (Examples)

The choice of specific technologies will depend on existing infrastructure, team expertise, and specific requirements.

| Component | Recommended Technologies (Examples) |

| :------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

| Error Capture (SDKs) | Sentry SDKs, Rollbar SDKs, custom libraries (e.g., log4j, Serilog, Winston wrappers) |

| Error Ingestion | AWS API Gateway / Azure API Management / Google Cloud Endpoints, Apache Kafka / AWS Kinesis / Azure Event Hubs / Google Pub/Sub, RabbitMQ |

| Error Processing | Apache Flink / Kafka Streams / AWS Kinesis Analytics / Azure Stream Analytics, custom microservices (Python/Java/Go) |

| Raw Error Storage | Elasticsearch / OpenSearch, Loki, Splunk, AWS CloudWatch Logs, Azure Log Analytics, Google Cloud Logging |

| Processed Error Storage| PostgreSQL, MongoDB, DynamoDB, Cassandra, Redis (for temporary state/deduplication) |

| Notification & Alerting| PagerDuty, Opsgenie, VictorOps, Slack Webhooks, Microsoft Teams Connectors, custom notification microservice, Prometheus Alertmanager (if integrated with metrics) |

| Dashboards & Reporting | Kibana, Grafana, Tableau, Power BI, custom React/Angular/Vue.js frontend |

| Resolution Workflow | Jira, ServiceNow, Zendesk, Asana, GitHub Issues |

| Configuration Mgmt. | Kubernetes ConfigMaps/Secrets, HashiCorp Vault, custom Admin UI backed by a configuration database (e.g., PostgreSQL) |

5. Integration Points

The Error Handling System must seamlessly integrate with:

  • Application Codebases: Via SDKs or logging frameworks.
  • CI/CD Pipelines: To automatically tag errors with deployment versions.
  • Monitoring Systems: To correlate errors with performance metrics and infrastructure health.
  • Identity & Access Management (IAM): For secure authentication and authorization.
  • Secret Management: For handling API keys and sensitive credentials.
  • Source Code Management (SCM): To link errors to specific code lines or commits.

6. Non-Functional Requirements

  • Scalability: Horizontal scaling for ingestion, processing, and storage components to handle peak loads.
  • High Availability: Redundant components, failover mechanisms, and disaster recovery planning.
  • Performance: Low latency for error ingestion and near real-time processing for critical alerts.
  • Security:

* Data Encryption: Encryption at rest and in transit (TLS/SSL).

* Access Control: Role-Based Access Control (RBAC) for managing who can view/modify error data.

* Data Masking/Anonymization: Mechanisms to redact sensitive PII or confidential information from error payloads before storage.

* Audit Logging: Track access and modifications to error data.

  • Maintainability: Well-documented APIs, modular design, and automated testing.
  • Observability: Comprehensive logging, metrics, and tracing for the Error Handling System itself.

7. High-Level Implementation Phases

  1. Phase 1: Foundation & Ingestion (Weeks 1-4)

* Define standardized error payload schema.

* Set up core ingestion components (API Gateway, Message Queue).

* Develop initial SDKs/adapters for a pilot application.

* Establish basic raw error storage (e.g., Elasticsearch cluster).

* Implement basic security measures (encryption, initial IAM).

  1. Phase 2: Processing & Core Functionality (Weeks 5-8)

* Develop stream processing for enrichment and deduplication.

* Set up processed error storage.

* Implement basic alerting rules and integrate with one notification channel (e.g., Slack).

* Develop initial dashboard views for error monitoring.

  1. Phase 3: Advanced Features & Integrations (Weeks 9-12)

* Integrate with ticketing systems (e.g., Jira).

* Implement advanced alerting rules and escalation policies.

* Develop more sophisticated dashboards and reporting.

* Expand SDK/adapter coverage to more applications.

* Implement data masking/anonymization capabilities.

* Refine RBAC and audit logging.

  1. Phase 4: Optimization & Rollout (Weeks 13+)

* Performance tuning and cost optimization.

* Comprehensive testing (load, integration, security).

* Documentation and training for development teams.

* Phased rollout to all applications and services.

* Establish ongoing maintenance and support procedures.

8. Next Steps

Upon approval of this architecture plan, the

gemini Output

Error Handling System: Comprehensive Deliverable

This document provides a detailed, production-ready implementation of a robust Error Handling System. It includes core principles, clean and well-commented code examples in Python, detailed explanations, and actionable integration instructions. This system is designed to provide consistent, informative, and secure error management across your applications.


1. Introduction

A well-designed error handling system is crucial for the reliability, maintainability, and user experience of any software application. It ensures that unforeseen issues are caught gracefully, users receive meaningful feedback, and developers have sufficient information to diagnose and resolve problems quickly.

This deliverable outlines an approach that emphasizes:

  • Consistency: All errors are handled and presented uniformly.
  • Clarity: Error messages are user-friendly while providing detailed logs for developers.
  • Centralization: A single point of control for error management.
  • Security: Prevents sensitive information leakage to end-users.
  • Extensibility: Easily adaptable to new error types and system requirements.

2. Key Principles of Robust Error Handling

Before diving into the code, understanding the foundational principles is essential:

  • Centralization: All errors, irrespective of where they originate, should ideally flow through a central handler. This ensures consistent logging, response formatting, and allows for global policies (e.g., rate limiting error responses).
  • Custom Exceptions: Define specific exception types for domain-specific errors. This makes your code more readable, allows for granular error handling, and provides more context than generic exceptions (e.g., ValueError, Exception).
  • Detailed Logging: Every error should be logged with sufficient context (timestamp, error type, message, stack trace, request details, user ID if applicable) to aid in debugging. Different log levels (ERROR, WARNING) should be used appropriately.
  • User-Friendly Responses: End-users should receive clear, concise, and actionable error messages without exposing sensitive internal details (e.g., stack traces, database schema). HTTP status codes should accurately reflect the nature of the error.
  • Graceful Degradation & Retries (Optional but Recommended): For transient errors (e.g., network issues, temporary service unavailability), consider implementing retry mechanisms with exponential backoff. For non-critical failures, the system should degrade gracefully rather than crashing entirely.
  • Monitoring & Alerting: Integrate your error handling system with monitoring tools (e.g., Prometheus, Grafana, Sentry, ELK Stack) to track error rates, identify trends, and trigger alerts for critical issues.

3. Production-Ready Code Implementation (Python Example)

The following Python code demonstrates a practical implementation of these principles. It includes custom exception classes, a centralized error handler with logging, and an example of how to integrate it into an application, particularly suitable for web APIs or microservices.

3.1. Custom Exception Definitions (app_exceptions.py)

This module defines custom exception classes that inherit from a common base exception. Each custom exception carries specific information like a user-friendly message, an HTTP status code, and optional detailed information for logging.


# app_exceptions.py

"""
Module for custom application-specific exceptions.
These exceptions provide structured error information for consistent handling.
"""

from http import HTTPStatus
from typing import Optional, Dict, Any

class BaseAppException(Exception):
    """
    Base class for all custom application exceptions.
    Provides a consistent structure for error messages and HTTP status codes.
    """
    def __init__(
        self,
        message: str = "An unexpected error occurred.",
        status_code: HTTPStatus = HTTPStatus.INTERNAL_SERVER_ERROR,
        details: Optional[Dict[str, Any]] = None
    ):
        """
        Initializes the BaseAppException.

        Args:
            message (str): A user-friendly message describing the error.
            status_code (HTTPStatus): The appropriate HTTP status code for the error.
            details (Optional[Dict[str, Any]]): Optional dictionary for additional
                                                technical details (e.g., validation errors).
        """
        super().__init__(message)
        self.message = message
        self.status_code = status_code
        self.details = details if details is not None else {}

    def to_dict(self) -> Dict[str, Any]:
        """
        Converts the exception into a dictionary suitable for API responses.
        """
        response = {
            "error": {
                "message": self.message,
                "code": self.status_code.value,
                "status": self.status_code.phrase
            }
        }
        if self.details:
            response["error"]["details"] = self.details
        return response

class InvalidInputError(BaseAppException):
    """
    Exception raised for invalid user input or request payload.
    Corresponds to HTTP 400 Bad Request.
    """
    def __init__(
        self,
        message: str = "Invalid input provided.",
        details: Optional[Dict[str, Any]] = None
    ):
        super().__init__(message, HTTPStatus.BAD_REQUEST, details)

class ResourceNotFoundError(BaseAppException):
    """
    Exception raised when a requested resource is not found.
    Corresponds to HTTP 404 Not Found.
    """
    def __init__(
        self,
        message: str = "The requested resource was not found.",
        resource_id: Optional[str] = None
    ):
        details = {"resource_id": resource_id} if resource_id else {}
        super().__init__(message, HTTPStatus.NOT_FOUND, details)

class UnauthorizedError(BaseAppException):
    """
    Exception raised when a user is not authenticated or authorized.
    Corresponds to HTTP 401 Unauthorized or 403 Forbidden.
    """
    def __init__(
        self,
        message: str = "Authentication required or credentials invalid.",
        details: Optional[Dict[str, Any]] = None,
        is_forbidden: bool = False # Use for 403 Forbidden
    ):
        status = HTTPStatus.FORBIDDEN if is_forbidden else HTTPStatus.UNAUTHORIZED
        super().__init__(message, status, details)

class ServiceUnavailableError(BaseAppException):
    """
    Exception raised when an external service is unavailable or unresponsive.
    Corresponds to HTTP 503 Service Unavailable.
    """
    def __init__(
        self,
        message: str = "Service is temporarily unavailable. Please try again later.",
        service_name: Optional[str] = None,
        original_error: Optional[Exception] = None
    ):
        details = {}
        if service_name:
            details["service"] = service_name
        if original_error:
            details["original_error_type"] = type(original_error).__name__
            details["original_error_message"] = str(original_error)
        super().__init__(message, HTTPStatus.SERVICE_UNAVAILABLE, details)

class InternalServerError(BaseAppException):
    """
    Generic exception for unexpected internal server errors not covered by other types.
    Corresponds to HTTP 500 Internal Server Error.
    """
    def __init__(
        self,
        message: str = "An unexpected internal server error occurred.",
        original_error: Optional[Exception] = None
    ):
        details = {}
        if original_error:
            details["original_error_type"] = type(original_error).__name__
            details["original_error_message"] = str(original_error)
        super().__init__(message, HTTPStatus.INTERNAL_SERVER_ERROR, details)

# You can add more specific exceptions as needed, e.g.,
# class DatabaseError(BaseAppException): ...
# class ConcurrencyError(BaseAppException): ...

3.2. Centralized Error Handler (error_handler.py)

This module provides a centralized mechanism to catch exceptions, log them, and format a consistent JSON response. It includes a simple logging setup and a decorator to easily apply error handling to functions.


# error_handler.py

"""
Centralized error handling module.
It provides logging capabilities and a decorator to wrap functions for
consistent error response generation.
"""

import logging
from functools import wraps
from http import HTTPStatus
from typing import Callable, Any, Dict, Optional

from app_exceptions import BaseAppException, InternalServerError

# --- Logger Configuration ---
# In a real application, you would configure logging more extensively,
# potentially using a separate config file or module.
# For demonstration, a basic console logger is set up here.
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# --- Centralized Error Handling Function ---
def handle_error(exception: Exception) -> Dict[str, Any]:
    """
    Processes an exception, logs it, and returns a structured error response.

    Args:
        exception (Exception): The exception that was caught.

    Returns:
        Dict[str, Any]: A dictionary representing the structured error response.
    """
    if isinstance(exception, BaseAppException):
        # Log custom application exceptions at WARNING level (or ERROR if critical)
        logger.warning(
            f"Application Error: {exception.status_code.value} - {exception.message}",
            exc_info=True, # Include stack trace in logs
            extra={"details": exception.details}
        )
        return exception.to_dict()
    else:
        # Log unhandled/unexpected exceptions at ERROR level
        # Wrap generic exceptions in InternalServerError to maintain consistency
        internal_error = InternalServerError(original_error=exception)
        logger.error(
            f"Unhandled Exception: {type(exception).__name__} - {str(exception)}",
            exc_info=True, # Always include stack trace for unhandled errors
            extra={"details": internal_error.details}
        )
        return internal_error.to_dict()

# --- Error Handling Decorator ---
def error_handler_decorator(func: Callable[..., Any]) -> Callable[..., Any]:
    """
    A decorator that wraps a function to catch exceptions and handle them
    using the centralized `handle_error` function.
    """
    @wraps(func)
    def wrapper(*args, **kwargs) -> Dict[str, Any]:
        try:
            result = func(*args, **kwargs)
            return result
        except Exception as e:
            # Catch any exception and pass it to the centralized handler
            return handle_error(e)
    return wrapper

# --- Example of an API-like response structure ---
def success_response(data: Any, status_code: HTTPStatus = HTTPStatus.OK) -> Dict[str, Any]:
    """
    Helper function to create a consistent success response structure.
    """
    return {
        "status": status_code.phrase,
        "code": status_code.value,
        "data": data
    }

3.3. Logging Configuration (logger_config.py - Optional, integrated into error_handler.py for simplicity)

While a basic logger is integrated into error_handler.py, for a production system, you would typically have a dedicated logging configuration.


# logger_config.py (Example - not strictly necessary if integrated as above)

import logging
import sys

def setup_logging(level=logging.INFO):
    """
    Sets up a basic logging configuration.
    In a real application, this would be more sophisticated (e.g., file handlers,
    log rotation, external logging services).
    """
    logging.basicConfig(
        level=level,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.StreamHandler(sys.stdout) # Output logs to console
            # logging.FileHandler("app.log"), # Example: uncomment for file logging
            # logging.handlers.RotatingFileHandler(...) # For log rotation
        ]
    )
    # Configure specific loggers if needed
    logging.getLogger("my_app_module").setLevel(logging.DEBUG)

# You would call setup_logging() once at application startup.

3.4. Example Application Integration (main_app.py)

This example demonstrates how to use the custom exceptions and the error handling decorator within a simple application function.


# main_app.py

"""
Example application demonstrating the usage of the error handling system.
"""

from http import HTTPStatus
from typing import Dict, Any

from app_exceptions import (
    InvalidInputError,
    ResourceNotFoundError,
    UnauthorizedError,
    ServiceUnavailableError,
    BaseAppException
)
from error_handler import error_handler_decorator, handle_error, success_response, logger

# --- Simulate a data store ---
mock_database = {
    "user_1": {"name": "Alice", "email": "alice@example.com"},
    "user_2": {"name": "Bob", "email": "bob@example.com"},
}

# --- Application Logic with Error Raising ---

@error_handler_decorator
def get_user_profile(user_id: str, auth_token: Optional[str] = None) -> Dict[str, Any]:
    """
    Retrieves a user profile by ID.
    Demonstrates raising custom exceptions based on business logic.
    """
    logger.info(f"Attempting to retrieve profile for user_id: {user_
gemini Output

Error Handling System: Comprehensive Review and Documentation

1. Executive Summary

This document provides a comprehensive review and detailed documentation of the proposed Error Handling System. Designed to enhance system robustness, improve user experience, and streamline operational efficiency, this system outlines a standardized approach to detecting, classifying, logging, and responding to errors across all integrated components. By implementing these guidelines and architectural principles, we aim to minimize downtime, expedite issue resolution, and maintain a high level of application stability and data integrity.

2. Introduction to the Error Handling System

An effective Error Handling System is crucial for any modern software application. It serves as the backbone for maintaining system reliability and providing a consistent user experience even in unexpected situations. This system is designed to:

  • Proactively Identify Issues: Catch errors before they lead to critical failures.
  • Provide Clear Feedback: Inform users and operators about issues in an understandable manner.
  • Facilitate Debugging and Resolution: Provide detailed context for developers to quickly diagnose and fix problems.
  • Ensure Data Integrity: Prevent corrupted data or inconsistent states.
  • Improve System Resilience: Allow applications to gracefully recover from transient errors.

3. Core Principles of Effective Error Handling

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

  • Consistency: A uniform approach to error handling across all modules and services.
  • Clarity: Error messages and logs must be clear, concise, and informative.
  • Graceful Degradation: The system should fail gracefully, minimizing impact on users and other services.
  • Actionability: Errors should provide sufficient context for operators or developers to take appropriate action.
  • Security: Avoid exposing sensitive system details in public error messages or logs.
  • Observability: Integrate with monitoring and alerting tools to ensure real-time visibility into error occurrences.
  • Recoverability: Prioritize strategies that allow for automatic or semi-automatic recovery from errors where possible.

4. Error Classification and Types

To ensure consistent handling, errors will be classified into distinct types:

  • Transient Errors:

* Definition: Temporary issues that are likely to resolve themselves with a retry (e.g., network glitches, temporary service unavailability, database deadlocks).

* Handling Strategy: Implement retry mechanisms with exponential backoff.

* Examples: HTTP 503 Service Unavailable, transient database connection timeouts.

  • Operational Errors:

* Definition: Predictable errors resulting from operational issues, often external to the application logic (e.g., invalid user input, missing configuration, permission denied, resource not found).

* Handling Strategy: Validate input, provide specific user feedback, log with relevant context, potentially trigger alerts for critical operational issues.

* Examples: HTTP 400 Bad Request, HTTP 404 Not Found, file not found.

  • Programming Errors (Bugs):

* Definition: Unexpected errors indicating a flaw in the application's code (e.g., null pointer exceptions, unhandled exceptions, logic errors).

* Handling Strategy: Catch at the highest possible level to prevent application crash, log full stack trace, trigger high-priority alerts, prevent data corruption.

* Examples: NullReferenceException, IndexError, unhandled runtime exceptions.

  • System Errors:

* Definition: Errors originating from the underlying infrastructure or operating system (e.g., out of memory, disk full, unrecoverable hardware failure).

* Handling Strategy: Log, alert system administrators, potentially initiate system shutdown or failover procedures.

* Examples: OutOfMemoryError, disk I/O errors.

5. Error Handling Strategies and Mechanisms

A multi-layered approach will be employed for handling errors:

5.1. Input Validation

  • Mechanism: Pre-emptive checks on all incoming data (API requests, user input, configuration files) at the earliest possible point.
  • Action: Reject invalid input with specific error codes and messages (e.g., HTTP 400 Bad Request), preventing further processing.
  • Benefit: Reduces the likelihood of internal application errors and improves security.

5.2. Try-Catch Blocks / Exception Handling

  • Mechanism: Standard language-specific exception handling constructs to gracefully manage expected and unexpected exceptions within code blocks.
  • Action:

* Catch Specific Exceptions: Handle known error conditions (e.g., file not found, network timeout) with tailored logic.

* Catch Generic Exceptions: Act as a fallback for unforeseen issues, ensuring the application doesn't crash.

* Log Context: Always log relevant variables, parameters, and stack traces.

  • Benefit: Prevents application crashes, allows for controlled recovery paths.

5.3. Retry Mechanisms

  • Mechanism: For transient errors, automatically re-attempt failed operations.
  • Action:

* Exponential Backoff: Increase delay between retries to avoid overwhelming the failing service.

* Jitter: Introduce randomness to backoff delays to prevent "thundering herd" problems.

* Max Retries: Define a maximum number of retries before classifying as a permanent failure.

* Circuit Breaker Pattern: Implement to prevent repeated calls to a failing service, allowing it time to recover.

  • Benefit: Improves resilience against temporary network or service disruptions.

5.4. Circuit Breaker Pattern

  • Mechanism: Monitors calls to external services. If a service fails repeatedly, the circuit opens, preventing further calls for a period.
  • Action:

* Open State: Requests fail fast without attempting to call the service.

* Half-Open State: Periodically allows a limited number of requests to test if the service has recovered.

* Closed State: Normal operation.

  • Benefit: Prevents cascading failures and allows failing services to recover without additional load.

5.5. Dead Letter Queues (DLQ)

  • Mechanism: For asynchronous messaging systems (e.g., Kafka, RabbitMQ), messages that fail processing after a defined number of retries are moved to a DLQ.
  • Action: Messages in the DLQ can be inspected, manually reprocessed, or analyzed for root cause.
  • Benefit: Ensures no messages are lost, even if processing fails repeatedly, and isolates problematic messages.

5.6. Transaction Management & Rollbacks

  • Mechanism: For operations involving multiple steps or data modifications, ensure atomicity.
  • Action: If any step within a transaction fails, all previous changes are rolled back to maintain data consistency.
  • Benefit: Guarantees data integrity and prevents partial updates.

5.7. User Feedback

  • Mechanism: Present clear, user-friendly error messages on the UI.
  • Action:

* Avoid technical jargon.

* Suggest actionable steps (e.g., "Please try again later," "Contact support with reference ID: XYZ").

* For security, do not expose internal system details.

  • Benefit: Improves user experience and reduces frustration.

6. Logging and Monitoring

A robust logging and monitoring infrastructure is critical for the Error Handling System.

6.1. Structured Logging

  • Mechanism: All error logs will be structured (e.g., JSON format) to facilitate machine parsing and analysis.
  • Content:

* Timestamp (UTC)

* Severity Level (FATAL, ERROR, WARN, INFO, DEBUG, TRACE)

* Unique Error Code (for programmatic identification)

* Error Message (human-readable)

* Contextual Data (e.g., user ID, request ID, transaction ID, affected component, specific parameters)

* Stack Trace (for programming errors)

* Hostname/Instance ID

  • Benefit: Enables efficient searching, filtering, and aggregation of logs.

6.2. Centralized Log Management

  • Mechanism: All application logs will be forwarded to a centralized log management system (e.g., ELK Stack, Splunk, Datadog).
  • Benefit: Provides a single pane of glass for log analysis, historical data retention, and compliance.

6.3. Alerting and Notifications

  • Mechanism: Integrate with monitoring tools to trigger alerts based on defined error thresholds or specific error patterns.
  • Action:

* Severity-based Thresholds: (e.g., >5 ERROR logs/minute for a service).

* Specific Error Codes: Alert on critical error codes immediately.

* Channels: Notifications via email, SMS, Slack, PagerDuty, etc., based on severity and escalation policies.

* On-Call Rotation: Ensure alerts reach the appropriate team members.

  • Benefit: Enables proactive incident response and reduces Mean Time To Recovery (MTTR).

6.4. Dashboards and Visualizations

  • Mechanism: Create dashboards to visualize error trends, frequency, and distribution across services.
  • Metrics: Error rates per service, top N errors, error latency, impact on user experience.
  • Benefit: Provides insights into system health and helps identify recurring issues or performance bottlenecks.

7. Implementation Guidelines for Developers

  • Use Standardized Error Objects/Enums: Define a common set of error codes and messages to ensure consistency across the application.
  • Don't Swallow Exceptions: Avoid catching exceptions and doing nothing. Always log, re-throw, or handle appropriately.
  • Fail Fast: When an unrecoverable error occurs, fail quickly and predictably rather than attempting to continue in a bad state.
  • Context is King: Always provide as much contextual information as possible in error logs.
  • External vs. Internal Errors: Differentiate between errors meant for end-users and detailed errors meant for developers/operators.
  • Testing Error Paths: Explicitly write unit and integration tests for error handling logic.
  • Documentation: Document error codes, their meanings, and recommended actions.

8. Testing and Validation

Thorough testing of the Error Handling System is paramount:

  • Unit Tests: Verify individual error handling logic within components.
  • Integration Tests: Simulate error conditions between services (e.g., a dependent service returning an error, network timeout) to test retry mechanisms, circuit breakers, and overall system resilience.
  • Chaos Engineering: Introduce controlled failures (e.g., kill a service, saturate CPU/memory) in production or staging environments to validate the system's ability to withstand and recover from unexpected events.
  • Negative Testing: Specifically test invalid inputs, missing configurations, and permission denied scenarios.

9. Maintenance and Evolution

The Error Handling System is not a static component; it must evolve with the application:

  • Regular Review: Periodically review error logs and dashboards to identify new error patterns or opportunities for improvement.
  • Post-Incident Reviews (PIRs): Analyze error handling effectiveness after major incidents and incorporate lessons learned.
  • Documentation Updates: Keep error codes, handling strategies, and escalation procedures up-to-date.
  • Tooling Updates: Evaluate and integrate new logging, monitoring, and alerting tools as they become available.

10. Benefits of a Robust Error Handling System

Implementing this comprehensive Error Handling System will deliver significant benefits:

  • Increased System Stability: Reduced crashes and unexpected behavior.
  • Improved User Experience: Clearer feedback and fewer disruptions for end-users.
  • Faster Incident Resolution: Detailed logs and proactive alerts enable quicker diagnosis and fixes.
  • Enhanced Data Integrity: Prevention of corrupted data due to partial operations.
  • Greater Operational Efficiency: Reduced manual intervention through automated retries and clear incident data.
  • Better Observability: Real-time insights into application health and performance.
  • Reduced Business Risk: Minimization of financial and reputational damage from system failures.

11. Next Steps and Recommendations

To proceed with the implementation and full realization of this Error Handling System, we recommend the following actionable steps:

  1. Finalize Error Code Catalog: Develop a comprehensive, standardized catalog of error codes with descriptions and suggested actions.
  2. Tooling Integration: Select and integrate preferred logging, monitoring, and alerting platforms (if not already in place).
  3. Developer Training: Conduct workshops for development teams on standardized error handling practices, logging guidelines, and tool usage.
  4. Pilot Implementation: Choose a critical service or module for a pilot implementation of the full error handling system, gather feedback, and iterate.
  5. Documentation Repository: Establish a central repository for all error handling documentation, including best practices, code examples, and escalation procedures.
  6. Monitoring & Alerting Configuration: Define specific alert rules and escalation paths for different error severities and types.
  7. Regular Review Cadence: Schedule regular meetings to review error trends, system performance, and refine the error handling strategy.

This detailed plan provides a solid foundation for building a resilient and maintainable Error Handling System that will significantly contribute to the overall success and reliability of your applications.

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
"); 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' import ReactDOM from 'react-dom/client' import App from './App' import './index.css' ReactDOM.createRoot(document.getElementById('root')!).render( ) "); 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' import './App.css' function App(){ return(

"+slugTitle(pn)+"

Built with PantheraHive BOS

) } export default App "); zip.file(folder+"src/index.css","*{margin:0;padding:0;box-sizing:border-box} body{font-family:system-ui,-apple-system,sans-serif;background:#f0f2f5;color:#1a1a2e} .app{min-height:100vh;display:flex;flex-direction:column} .app-header{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:40px} h1{font-size:2.5rem;font-weight:700} "); 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)+" Generated by PantheraHive BOS. ## Setup ```bash npm install npm run dev ``` ## Build ```bash npm run build ``` ## Open in IDE Open the project folder in VS Code or WebStorm. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local "); } /* --- 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",'{ "name": "'+pn+'", "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vue-tsc -b && vite build", "preview": "vite preview" }, "dependencies": { "vue": "^3.5.13", "vue-router": "^4.4.5", "pinia": "^2.3.0", "axios": "^1.7.9" }, "devDependencies": { "@vitejs/plugin-vue": "^5.2.1", "typescript": "~5.7.3", "vite": "^6.0.5", "vue-tsc": "^2.2.0" } } '); zip.file(folder+"vite.config.ts","import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { resolve } from 'path' export default defineConfig({ plugins: [vue()], resolve: { alias: { '@': resolve(__dirname,'src') } } }) "); zip.file(folder+"tsconfig.json",'{"files":[],"references":[{"path":"./tsconfig.app.json"},{"path":"./tsconfig.node.json"}]} '); zip.file(folder+"tsconfig.app.json",'{ "compilerOptions":{ "target":"ES2020","useDefineForClassFields":true,"module":"ESNext","lib":["ES2020","DOM","DOM.Iterable"], "skipLibCheck":true,"moduleResolution":"bundler","allowImportingTsExtensions":true, "isolatedModules":true,"moduleDetection":"force","noEmit":true,"jsxImportSource":"vue", "strict":true,"paths":{"@/*":["./src/*"]} }, "include":["src/**/*.ts","src/**/*.d.ts","src/**/*.tsx","src/**/*.vue"] } '); zip.file(folder+"env.d.ts","/// "); zip.file(folder+"index.html"," "+slugTitle(pn)+"
"); 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' import { createPinia } from 'pinia' import App from './App.vue' import './assets/main.css' const app = createApp(App) app.use(createPinia()) app.mount('#app') "); var hasApp=Object.keys(extracted).some(function(k){return k.indexOf("App.vue")>=0;}); if(!hasApp) zip.file(folder+"src/App.vue"," "); 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} "); 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)+" Generated by PantheraHive BOS. ## Setup ```bash npm install npm run dev ``` ## Build ```bash npm run build ``` Open in VS Code or WebStorm. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local "); } /* --- 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",'{ "name": "'+pn+'", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test" }, "dependencies": { "@angular/animations": "^19.0.0", "@angular/common": "^19.0.0", "@angular/compiler": "^19.0.0", "@angular/core": "^19.0.0", "@angular/forms": "^19.0.0", "@angular/platform-browser": "^19.0.0", "@angular/platform-browser-dynamic": "^19.0.0", "@angular/router": "^19.0.0", "rxjs": "~7.8.0", "tslib": "^2.3.0", "zone.js": "~0.15.0" }, "devDependencies": { "@angular-devkit/build-angular": "^19.0.0", "@angular/cli": "^19.0.0", "@angular/compiler-cli": "^19.0.0", "typescript": "~5.6.0" } } '); zip.file(folder+"angular.json",'{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "'+pn+'": { "projectType": "application", "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:application", "options": { "outputPath": "dist/'+pn+'", "index": "src/index.html", "browser": "src/main.ts", "tsConfig": "tsconfig.app.json", "styles": ["src/styles.css"], "scripts": [] } }, "serve": {"builder":"@angular-devkit/build-angular:dev-server","configurations":{"production":{"buildTarget":"'+pn+':build:production"},"development":{"buildTarget":"'+pn+':build:development"}},"defaultConfiguration":"development"} } } } } '); zip.file(folder+"tsconfig.json",'{ "compileOnSave": false, "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"]}, "references":[{"path":"./tsconfig.app.json"}] } '); zip.file(folder+"tsconfig.app.json",'{ "extends":"./tsconfig.json", "compilerOptions":{"outDir":"./dist/out-tsc","types":[]}, "files":["src/main.ts"], "include":["src/**/*.d.ts"] } '); zip.file(folder+"src/index.html"," "+slugTitle(pn)+" "); zip.file(folder+"src/main.ts","import { bootstrapApplication } from '@angular/platform-browser'; import { appConfig } from './app/app.config'; import { AppComponent } from './app/app.component'; bootstrapApplication(AppComponent, appConfig) .catch(err => console.error(err)); "); zip.file(folder+"src/styles.css","* { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: system-ui, -apple-system, sans-serif; background: #f9fafb; color: #111827; } "); 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'; import { RouterOutlet } from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [RouterOutlet], templateUrl: './app.component.html', styleUrl: './app.component.css' }) export class AppComponent { title = '"+pn+"'; } "); zip.file(folder+"src/app/app.component.html","

"+slugTitle(pn)+"

Built with PantheraHive BOS

"); 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} "); } zip.file(folder+"src/app/app.config.ts","import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; export const appConfig: ApplicationConfig = { providers: [ provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes) ] }; "); zip.file(folder+"src/app/app.routes.ts","import { Routes } from '@angular/router'; export const routes: Routes = []; "); 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)+" Generated by PantheraHive BOS. ## Setup ```bash npm install ng serve # or: npm start ``` ## Build ```bash ng build ``` Open in VS Code with Angular Language Service extension. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local .angular/ "); } /* --- Python --- */ function buildPython(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^```[w]* ?/m,"").replace(/ ?```$/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(" "):"# add dependencies here "; zip.file(folder+"main.py",src||"# "+title+" # Generated by PantheraHive BOS print(title+" loaded") "); zip.file(folder+"requirements.txt",reqsTxt); zip.file(folder+".env.example","# Environment variables "); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Setup ```bash python3 -m venv .venv source .venv/bin/activate pip install -r requirements.txt ``` ## Run ```bash python main.py ``` "); zip.file(folder+".gitignore",".venv/ __pycache__/ *.pyc .env .DS_Store "); } /* --- Node.js --- */ function buildNode(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^```[w]* ?/m,"").replace(/ ?```$/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)+" "; zip.file(folder+"package.json",pkgJson); var fallback="const express=require("express"); const app=express(); app.use(express.json()); app.get("/",(req,res)=>{ res.json({message:""+title+" API"}); }); const PORT=process.env.PORT||3000; app.listen(PORT,()=>console.log("Server on port "+PORT)); "; zip.file(folder+"src/index.js",src||fallback); zip.file(folder+".env.example","PORT=3000 "); zip.file(folder+".gitignore","node_modules/ .env .DS_Store "); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Setup ```bash npm install ``` ## Run ```bash npm run dev ``` "); } /* --- 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:" "+title+" "+code+" "; zip.file(folder+"index.html",indexHtml); zip.file(folder+"style.css","/* "+title+" — styles */ *{margin:0;padding:0;box-sizing:border-box} body{font-family:system-ui,-apple-system,sans-serif;background:#fff;color:#1a1a2e} "); zip.file(folder+"script.js","/* "+title+" — scripts */ "); zip.file(folder+"assets/.gitkeep",""); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Open Double-click `index.html` in your browser. Or serve locally: ```bash npx serve . # or python3 -m http.server 3000 ``` "); zip.file(folder+".gitignore",".DS_Store node_modules/ .env "); } /* ===== 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(/ {2,}/g,"

"); h+="

"+hc+"

Generated by PantheraHive BOS
"; zip.file(folder+app+".html",h); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. Files: - "+app+".md (Markdown) - "+app+".html (styled HTML) "); } 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);}});}