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

This document outlines the architectural plan for a robust and scalable Error Handling System, aligning with "Step 1: Architecture Planning" of your workflow.


Step 1: Architecture Plan for "Error Handling System"

1. Introduction and Purpose

A well-designed error handling system is crucial for the reliability, maintainability, and observability of any software application. This document details a comprehensive architectural plan for an "Error Handling System" designed to efficiently capture, process, store, notify, and analyze errors across your applications. The goal is to minimize downtime, improve debugging efficiency, enhance user experience by proactive issue resolution, and provide valuable insights into system health.

2. Clarification on Scope

Please Note: The current step is explicitly defined as plan_architecture for the "Error Handling System". While your prompt also included instructions for creating a "detailed study plan," the primary focus of this deliverable, as per the workflow step, is the system architecture. We have therefore prioritized the architectural design. If a detailed study plan is indeed required, please submit it as a separate request or specify it in a dedicated workflow step.

3. Core Architectural Principles

The proposed architecture will adhere to the following principles:

4. High-Level System Architecture Overview

The Error Handling System will be structured into several interconnected components, working together to manage the entire error lifecycle.

mermaid • 465 chars
graph TD
    A[Application/Service 1] --> B(Error Capture SDK/Agent)
    C[Application/Service N] --> B
    B --> D[Error Ingestion API/Gateway]
    D --> E[Message Queue/Stream]
    E --> F[Error Processing & Enrichment Service]
    F --> G[Error Storage (Database/Search Index)]
    G --> H[Notification & Alerting Engine]
    G --> I[Dashboard & Reporting Interface]
    H --> J[Alert Channels (Email, Slack, PagerDuty)]
    I --> K[Developers/Operations Teams]
Sandboxed live preview

5. Detailed Component Breakdown

5.1. Error Source / Application Layer

  • Function: The origin of errors within your applications and services (e.g., frontend, backend, mobile apps, microservices, batch jobs).
  • Key Considerations:

* Language/Framework Agnostic: Support for diverse technology stacks.

* Performance Impact: Minimal overhead on the application's runtime.

* Contextual Data: Ability to attach relevant metadata (user ID, request ID, environment, custom tags) to errors.

  • Potential Technologies:

* Native logging libraries (Log4j, Serilog, Winston, Python logging).

* Dedicated error tracking SDKs (Sentry, Rollbar, Bugsnag).

* Custom instrumentation for specific error types or business logic failures.

5.2. Error Capture & Context Enrichment

  • Function: Intercepts errors at the source, gathers necessary context (stack trace, environment variables, user information, request details), and formats the error data.
  • Key Considerations:

* Robustness: Should not crash the application even if the error handling system is unavailable.

* Data Masking: Ability to redact sensitive information (PII, API keys) before transmission.

* Offline Caching: Temporarily store errors if the network is unavailable.

  • Potential Technologies:

* SDKs/Agents: Provided by commercial error trackers or custom-built wrappers around logging frameworks.

* AOP (Aspect-Oriented Programming): For injecting error capture logic without modifying core business code.

5.3. Error Ingestion API / Gateway

  • Function: A highly available and scalable endpoint that receives error data from various applications. It acts as the entry point to the error handling system.
  • Key Considerations:

* Rate Limiting: Protects the system from being overwhelmed by a flood of errors.

* Authentication/Authorization: Securely identifies and validates incoming error reports.

* Payload Validation: Ensures received data conforms to expected schema.

* Endpoint Scalability: Horizontally scalable to handle spikes in error volume.

  • Potential Technologies:

* API Gateway: AWS API Gateway, Azure API Management, NGINX, Kong.

* Load Balancers: Distribute traffic across multiple ingestion service instances.

* Lightweight Microservice: A dedicated service for receiving and initial processing.

5.4. Message Queue / Stream

  • Function: Decouples the ingestion process from downstream processing, providing buffering, fault tolerance, and enabling asynchronous operations.
  • Key Considerations:

* Durability: Persist messages to prevent data loss.

* Ordering (Optional): Maintain the order of errors if required for specific analysis.

* Scalability: Handle high throughput of messages.

* Fan-out: Allow multiple consumers to process the same error stream.

  • Potential Technologies:

* Apache Kafka: High-throughput, fault-tolerant, distributed streaming platform.

* RabbitMQ: Robust, general-purpose message broker.

* AWS SQS/SNS, Azure Service Bus, Google Cloud Pub/Sub: Managed cloud messaging services.

5.5. Error Processing & Enrichment Service

  • Function: Consumes error messages from the queue, performs further processing, enrichment, and deduplication.

* Deduplication: Groups identical errors to reduce noise.

* Stack Trace Normalization: Standardize stack traces across different languages/environments.

* Source Map Resolution: For frontend errors, resolve minified code to original source.

* Tagging/Categorization: Automatically assign tags based on error type, application, or severity.

* Contextual Lookups: Add external data (e.g., user profile data, deployment version).

  • Key Considerations:

* Idempotency: Processing should be repeatable without side effects.

* Error Handling within Service: Gracefully handle malformed messages.

* Scalability: Horizontally scalable to process messages quickly.

  • Potential Technologies:

* Microservices: Implemented in Go, Python, Java, Node.js.

* Stream Processing Frameworks: Apache Flink, Spark Streaming (for complex real-time analysis).

* Serverless Functions: AWS Lambda, Azure Functions, Google Cloud Functions for event-driven processing.

5.6. Error Storage (Database / Search Index)

  • Function: Persistently stores processed error data, making it queryable for analysis, reporting, and historical lookup.
  • Key Considerations:

* Indexing: Optimized for fast searches and aggregations (e.g., by error type, application, timestamp, user).

* Scalability: Handle large volumes of data and growing retention requirements.

* Data Retention Policies: Support automated data archiving or deletion.

* Cost Efficiency: Balance performance with storage costs.

  • Potential Technologies:

* Elasticsearch: Excellent for full-text search, aggregations, and time-series data (often paired with Kibana).

* MongoDB/Cassandra: NoSQL databases for flexible schema and high write throughput.

* PostgreSQL/MySQL: Relational databases for structured data, potentially with JSONB columns for flexible schema.

* Time-Series Databases: InfluxDB, Prometheus (though Prometheus is primarily for metrics).

5.7. Notification & Alerting Engine

  • Function: Evaluates incoming processed errors against predefined rules and triggers alerts to relevant teams or systems.
  • Key Considerations:

* Rule Engine: Flexible rule definition (e.g., "N errors of type X in M minutes," "new error type detected").

* Thresholds: Configurable thresholds for alert severity and frequency.

* Downtime Management: Suppress alerts during planned maintenance.

* Escalation Policies: Define escalating alert paths for critical issues.

  • Potential Technologies:

* Prometheus Alertmanager: Open-source alerting system.

* Custom Microservice: With a rules engine (e.g., based on Drools, or simple IF-THEN logic).

* Managed Services: AWS CloudWatch Alarms, Azure Monitor Alerts.

5.8. Dashboard & Reporting Interface

  • Function: Provides a user interface for visualizing error trends, drilling down into specific errors, searching historical data, and generating reports.
  • Key Considerations:

* Intuitive UI: Easy to navigate for developers and operations teams.

* Customizable Dashboards: Allow users to create personalized views.

* Powerful Search & Filtering: Enable complex queries on error data.

* Role-Based Access Control (RBAC): Restrict access to sensitive error data.

* Integration with Incident Management: Link errors to tickets in JIRA, ServiceNow, etc.

  • Potential Technologies:

* Kibana: For Elasticsearch-based storage.

* Grafana: For visualizing data from various sources (including Elasticsearch, Prometheus, SQL).

* Custom Web Application: Built with React, Angular, Vue.js, backed by a REST API.

* Commercial Tools: Sentry, Rollbar, Bugsnag (if using an integrated solution).

5.9. (Optional) Automated Remediation Hooks

  • Function: Integrates with automation systems to trigger predefined actions based on specific error patterns (e.g., restart a service, scale up resources, roll back a deployment).
  • Key Considerations:

* Safety: Ensure automated actions are thoroughly tested and safe.

* Audit Trail: Log all automated actions.

* Configuration: Define triggers and corresponding actions.

  • Potential Technologies:

* Webhook integrations: To CI/CD pipelines, serverless functions, or orchestration tools.

* Runbook Automation: Ansible, Chef, Puppet.

6. Data Flow and Lifecycle

  1. Error Occurrence: An error occurs in an application.
  2. Capture & Enrich: The Error Capture SDK/Agent intercepts the error, gathers context, redacts sensitive data, and formats it into a standardized payload.
  3. Ingestion: The formatted error payload is sent to the Error Ingestion API/Gateway.
  4. Queueing: The Ingestion API validates the payload and publishes it to a Message Queue/Stream.
  5. Processing: The Error Processing & Enrichment Service consumes messages from the queue, performs deduplication, normalization, and further enrichment.
  6. Storage: Processed errors are stored in the Error Storage (e.g., Elasticsearch).
  7. Alerting: The Notification & Alerting Engine continuously monitors new errors in storage, evaluates them against predefined rules, and triggers alerts if thresholds are met.
  8. Notification: Alerts are dispatched to relevant Alert Channels (Email, Slack, PagerDuty, etc.).
  9. Visualization & Analysis:
gemini Output

This document outlines a comprehensive and robust Error Handling System, providing detailed explanations, production-ready code examples, and best practices. This system is designed to improve application stability, maintainability, and user experience by systematically identifying, logging, and responding to errors.

Error Handling System: Detailed Implementation Plan

A well-architected error handling system is crucial for any production application. It ensures that failures are gracefully managed, users receive appropriate feedback, and developers have the necessary information to diagnose and resolve issues efficiently.

1. Core Principles of a Robust Error Handling System

Before diving into implementation, it's essential to understand the guiding principles:

  • Clarity & Specificity: Errors should clearly indicate what went wrong, where, and why.
  • Centralization: All errors should ideally be processed through a single, consistent mechanism.
  • Graceful Degradation: The system should prevent cascading failures and maintain as much functionality as possible during an error.
  • Logging & Monitoring: Critical error information must be logged for post-mortem analysis and monitored for real-time alerting.
  • User Experience: Users should receive clear, non-technical, and helpful feedback without exposing sensitive system details.
  • Security: Prevent information leakage (e.g., stack traces, sensitive data) in public-facing error messages.
  • Actionability: Error reports should contain enough context for developers to take immediate action.

2. Key Components of the System

Our error handling system will consist of the following integrated components:

  1. Custom Exception Classes: Define application-specific exceptions to categorize and handle different types of errors programmatically.
  2. Centralized Error Handling Mechanism: A global handler (e.g., middleware, decorator, centralized function) to catch, process, and respond to exceptions consistently.
  3. Logging & Monitoring Integration: Integrate with a robust logging framework to record error details, stack traces, and contextual information.
  4. Standardized Error Responses: Define a consistent structure for error messages returned to clients (especially for APIs).
  5. Alerting & Notification: Integrate with external services (e.g., Slack, PagerDuty, email) for critical error notifications.
  6. User Feedback & Presentation: Mechanisms to display user-friendly error messages in the UI.

3. Code Implementation (Python Example)

We will use Python for the code examples, demonstrating how to implement these components in a modular and scalable way. The examples are designed to be general-purpose but will include specific considerations for web applications (e.g., API responses).

3.1. Custom Exception Definitions

Defining custom exceptions allows for more granular error handling and makes the codebase more readable. We'll create a base application exception and derive specific error types from it.


# errors/exceptions.py

import json

class AppError(Exception):
    """
    Base class for all application-specific errors.
    All custom errors should inherit from this class.
    """
    def __init__(self, message="An application error occurred.", status_code=500, payload=None, error_code="GENERIC_ERROR"):
        super().__init__(message)
        self.message = message
        self.status_code = status_code
        self.payload = payload if payload is not None else {}
        self.error_code = error_code # A unique, internal error code

    def to_dict(self):
        """
        Converts the exception details into a dictionary suitable for API responses.
        """
        res = {
            "error_code": self.error_code,
            "message": self.message
        }
        if self.payload:
            res["details"] = self.payload
        return res

    def __str__(self):
        return f"AppError(code={self.error_code}, status={self.status_code}, message='{self.message}')"

class ValidationError(AppError):
    """
    Error raised for invalid input or data validation failures.
    """
    def __init__(self, message="Invalid input provided.", details=None):
        super().__init__(message, status_code=400, payload=details, error_code="VALIDATION_ERROR")

class NotFoundError(AppError):
    """
    Error raised when a requested resource is not found.
    """
    def __init__(self, message="Resource not found.", resource_id=None):
        payload = {"resource_id": resource_id} if resource_id else {}
        super().__init__(message, status_code=404, payload=payload, error_code="NOT_FOUND")

class UnauthorizedError(AppError):
    """
    Error raised when a user is not authenticated or authorized to perform an action.
    """
    def __init__(self, message="Authentication required or not authorized.", details=None):
        super().__init__(message, status_code=401, payload=details, error_code="UNAUTHORIZED")

class ForbiddenError(AppError):
    """
    Error raised when a user is authenticated but does not have the necessary permissions.
    """
    def __init__(self, message="You do not have permission to access this resource.", details=None):
        super().__init__(message, status_code=403, payload=details, error_code="FORBIDDEN")

class ServiceUnavailableError(AppError):
    """
    Error raised when an external service is unavailable or unresponsive.
    """
    def __init__(self, message="Service temporarily unavailable. Please try again later.", service_name=None):
        payload = {"service": service_name} if service_name else {}
        super().__init__(message, status_code=503, payload=payload, error_code="SERVICE_UNAVAILABLE")

class DatabaseError(AppError):
    """
    Error raised for database-related issues.
    """
    def __init__(self, message="A database error occurred.", original_error=None):
        payload = {"original_error": str(original_error)} if original_error else {}
        super().__init__(message, status_code=500, payload=payload, error_code="DATABASE_ERROR")

class ExternalAPIError(AppError):
    """
    Error raised when an external API call fails.
    """
    def __init__(self, message="An external API call failed.", api_name=None, status_code=502):
        payload = {"api_name": api_name} if api_name else {}
        super().__init__(message, status_code=status_code, payload=payload, error_code="EXTERNAL_API_ERROR")

3.2. Logging Configuration

A robust logging setup is critical for capturing detailed error information.


# config/logging_config.py

import logging
import os
from logging.handlers import RotatingFileHandler

def setup_logging(log_level=logging.INFO, log_file='app.log', max_bytes=10*1024*1024, backup_count=5):
    """
    Configures the application's logging system.

    Args:
        log_level (int): The minimum logging level to capture (e.g., logging.INFO, logging.DEBUG).
        log_file (str): The name of the log file.
        max_bytes (int): Maximum size of the log file before rotation (in bytes).
        backup_count (int): Number of old log files to keep.
    """
    # Ensure log directory exists
    log_dir = 'logs'
    os.makedirs(log_dir, exist_ok=True)
    log_path = os.path.join(log_dir, log_file)

    # Get the root logger
    logger = logging.getLogger()
    logger.setLevel(log_level)

    # Clear existing handlers to prevent duplicate logs if called multiple times
    if logger.handlers:
        for handler in logger.handlers:
            logger.removeHandler(handler)

    # Create a formatter
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(module)s:%(funcName)s:%(lineno)d - %(message)s'
    )

    # Console Handler
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO) # Console might be less verbose than file
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)

    # File Handler for general logs
    file_handler = RotatingFileHandler(log_path, maxBytes=max_bytes, backupCount=backup_count)
    file_handler.setLevel(log_level)
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)

    # Specific error file handler (optional, for critical errors)
    error_file_handler = RotatingFileHandler(os.path.join(log_dir, 'error.log'), maxBytes=max_bytes, backupCount=backup_count)
    error_file_handler.setLevel(logging.ERROR)
    error_file_handler.setFormatter(formatter)
    logger.addHandler(error_file_handler)

    logging.info("Logging system initialized.")

# Example usage:
# from config.logging_config import setup_logging
# setup_logging(log_level=logging.DEBUG)
# logger = logging.getLogger(__name__)
# logger.debug("This is a debug message.")
# logger.error("This is an error message.")

3.3. Centralized Error Handler (Framework-Agnostic & Flask Example)

This component is responsible for catching exceptions, logging them, and generating appropriate responses.

##### 3.3.1. General-Purpose Error Handler Function


# handlers/error_handler.py

import logging
from errors.exceptions import AppError
from http import HTTPStatus # Python 3.5+ for symbolic HTTP status codes

logger = logging.getLogger(__name__)

def handle_exception(e: Exception, request_info: dict = None, debug_mode: bool = False):
    """
    Centralized exception handler. Processes exceptions, logs them,
    and returns a standardized error response.

    Args:
        e (Exception): The exception object caught.
        request_info (dict, optional): Contextual information about the request (e.g., path, method, user_id).
        debug_mode (bool): If True, include more detailed error info (e.g., stack trace) in logs.

    Returns:
        tuple: A tuple containing (response_body_dict, status_code).
    """
    status_code = HTTPStatus.INTERNAL_SERVER_ERROR
    response_payload = {
        "error_code": "GENERIC_ERROR",
        "message": "An unexpected error occurred. Please try again later."
    }
    log_level = logging.ERROR

    if isinstance(e, AppError):
        # Handle custom application errors
        status_code = e.status_code
        response_payload = e.to_dict()
        if status_code < 500: # Client errors (4xx) are typically INFO/WARNING
            log_level = logging.INFO
        logger.log(log_level, f"Application Error: {e.error_code} - {e.message}", exc_info=debug_mode, extra={'request_info': request_info})
    else:
        # Handle unexpected system errors
        # Log the full traceback for unhandled exceptions
        logger.exception(f"Unhandled System Error: {str(e)}", extra={'request_info': request_info})
        if debug_mode:
            response_payload["message"] = f"Internal Server Error: {str(e)}"
            # In a real system, avoid exposing raw error messages to production clients
            # For debugging, you might include more details.
            # response_payload["details"] = traceback.format_exc() # Requires import traceback

    # Always log the error, even if it's a client error, for auditing
    logger.log(log_level, f"Error Response - Status: {status_code}, Payload: {response_payload}")

    return response_payload, status_code

# Example of how you might use it in a generic function:
def some_operation(data, debug=False):
    try:
        if not data:
            raise ValidationError("Data cannot be empty.")
        if data == "fail_not_found":
            raise NotFoundError("Item not found.", resource_id="XYZ")
        if data == "fail_unauthorized":
            raise UnauthorizedError("Invalid API key.")
        if data == "fail_db":
            raise DatabaseError("Failed to connect to DB", original_error=Exception("Connection refused"))
        if data == "fail_unknown":
            # Simulate an unexpected system error
            return 1 / 0
        return {"status": "success", "data": data}
    except Exception as e:
        req_info = {"path": "/api/some_operation", "method": "POST", "user_agent": "test-client"}
        response_body, status = handle_exception(e, request_info=req_info, debug_mode=debug)
        return {"error_response": response_body, "status_code": status}

##### 3.3.2. Flask Web Framework Integration Example

For web frameworks, error handlers are typically registered to catch exceptions that occur during request processing.


# app.py (Example Flask Application)

from flask import Flask, jsonify, request
import logging
from config.logging_config import setup_logging
from errors.exceptions import (
    AppError, ValidationError, NotFoundError, UnauthorizedError,
    ForbiddenError, ServiceUnavailableError, DatabaseError, ExternalAPIError
)
from handlers.error_handler import handle_exception
import os

# Setup logging first
setup_logging(log_level=logging.DEBUG if os.getenv('FLASK_ENV') == 'development' else logging.INFO)
logger = logging
gemini Output

This document outlines the comprehensive Error Handling System designed to enhance the reliability, stability, and maintainability of your applications and services. This system provides a structured approach to identifying, logging, notifying, and resolving errors efficiently, minimizing impact on users and operations.


1. Executive Summary

The Error Handling System is a critical framework designed to proactively manage and mitigate issues across your software ecosystem. By centralizing error capture, classification, logging, and alerting, this system significantly improves operational visibility, reduces mean time to resolution (MTTR), and supports a robust incident management process. It ensures that errors are not just caught, but systematically addressed, leading to more stable applications and an improved user experience.


2. Introduction to the Error Handling System

2.1. Purpose

The primary purpose of this Error Handling System is to establish a standardized, robust, and scalable mechanism for dealing with exceptions and errors across all integrated applications. It aims to:

  • Enhance Reliability: Ensure applications remain stable even under unexpected conditions.
  • Improve Maintainability: Provide clear, actionable insights for developers to quickly diagnose and fix issues.
  • Reduce Downtime: Enable rapid detection and response to critical errors, minimizing service interruptions.
  • Increase Visibility: Offer a centralized view of error occurrences, trends, and impacts.
  • Support Proactive Management: Shift from reactive firefighting to proactive issue resolution and prevention.

2.2. Scope

This system covers:

  • Runtime Errors: Exceptions, crashes, and unexpected behavior within application code.
  • API Errors: Issues arising from internal and external API communications.
  • Infrastructure Errors: Problems related to databases, network, and underlying services (where detectable by application logic).
  • User Interface Errors: Client-side errors (e.g., JavaScript errors in web applications).

2.3. Key Objectives

  • Standardize error capture and reporting.
  • Implement intelligent error classification and severity assignment.
  • Establish efficient logging and storage solutions.
  • Develop configurable and timely alerting mechanisms.
  • Define clear workflows for error investigation and resolution.
  • Provide dashboards and reports for monitoring and analysis.

3. System Architecture and Components

The Error Handling System is composed of several interconnected components designed for modularity, scalability, and efficiency.

3.1. High-Level Architecture

The system follows a typical pattern of error interception, processing, storage, and notification.


graph TD
    A[Application/Service] --> B{Error Interception};
    B --> C[Error Standardizer & Classifier];
    C --> D[Logging & Persistence Service];
    D --> E[Alerting & Notification Engine];
    D --> F[Monitoring & Analytics Dashboard];
    E --> G{Incident Management System / On-Call Paging};
    F --> H[Reporting & Trend Analysis];
    G --> I[Developer / Operations Team];
    H --> I;

3.2. Core Components

  • 3.2.1. Error Interceptors/Handlers:

* Purpose: Catch errors at the earliest possible point within the application lifecycle (e.g., global exception handlers, middleware, API gateway filters, try-catch blocks).

* Functionality: Capture relevant context (stack trace, request details, user info, environment variables).

  • 3.2.2. Error Standardizer & Classifier:

* Purpose: Transform raw error data into a standardized format and assign classification attributes.

* Functionality:

* Normalize error messages and stack traces.

* Assign unique error codes.

* Determine severity (Critical, High, Medium, Low, Informational).

* Categorize by type (e.g., Database, Network, Business Logic, UI).

  • 3.2.3. Logging & Persistence Service:

* Purpose: Securely store structured error logs for historical analysis and debugging.

* Technology Examples: Centralized Log Management (CLM) systems like ELK Stack (Elasticsearch, Logstash, Kibana), Splunk, Datadog, or cloud-native solutions (e.g., AWS CloudWatch Logs, Azure Monitor Logs, Google Cloud Logging).

* Functionality:

* Ingest standardized error payloads.

* Index logs for fast searching and filtering.

* Implement data retention policies.

  • 3.2.4. Alerting & Notification Engine:

* Purpose: Proactively inform relevant teams about critical errors based on predefined rules.

* Functionality:

* Trigger alerts based on error severity, frequency, or specific patterns.

* Support multiple notification channels.

* Manage escalation policies.

  • 3.2.5. Monitoring & Analytics Dashboard:

* Purpose: Provide real-time visibility into error trends, volumes, and impacts.

* Functionality:

* Visualize error rates, top errors, and affected components.

* Allow drill-down into individual error details.

* Track key error-related metrics.


4. Error Identification and Classification

4.1. Error Capture Mechanisms

  • Global Exception Handlers: Catch unhandled exceptions at the application level (e.g., ASP.NET Core middleware, Spring Boot @ControllerAdvice, Node.js Express error middleware).
  • Specific Try-Catch Blocks: For expected but exceptional conditions within business logic.
  • API Gateway/Proxy Level: Capture upstream service errors or malformed requests.
  • Client-Side Error Reporting: JavaScript window.onerror or dedicated client-side error tracking libraries (e.g., Sentry, Bugsnag).
  • Asynchronous Process Monitoring: For background jobs and message queue consumers.

4.2. Standardized Error Data Model

All captured errors will be transformed into a consistent JSON payload before logging, including:

  • timestamp: UTC time of error occurrence.
  • serviceName: Name of the service/application where the error occurred.
  • environment: (e.g., production, staging, development).
  • transactionId / requestId: Unique identifier for the request/operation.
  • errorCode: Standardized alphanumeric code (e.g., APP-001, DB-102).
  • errorMessage: Human-readable summary of the error.
  • errorType: Categorization (e.g., System, BusinessLogic, Network, Database).
  • severity: (e.g., Critical, High, Medium, Low, Informational).
  • stackTrace: Full stack trace of the exception.
  • context:

* userId (if applicable and anonymized).

* requestUrl, httpMethod, headers, body (sanitized).

* component / module.

* Any other relevant application-specific data.

4.3. Error Classification and Severity Levels

Errors are classified to enable efficient prioritization and response.

  • Critical: Immediate service outage, data corruption, major security breach. Requires immediate, 24/7 attention.
  • High: Significant degradation of service, major functionality impaired for a subset of users, potential data loss. Requires urgent attention during business hours, on-call notification.
  • Medium: Minor functionality impaired, performance degradation, non-critical data inconsistency. Requires attention within business hours.
  • Low: Cosmetic issues, minor UI glitches, non-impactful warnings. Can be addressed in regular development cycles.
  • Informational: Expected conditions, audit trails, successful operations that are part of a larger flow. Typically for logging purposes only.

5. Logging and Persistence Strategy

5.1. Structured Logging

All error logs will adhere to a structured logging format (e.g., JSON) to facilitate machine readability, querying, and analysis. This ensures consistency across different services and languages.

5.2. Centralized Log Management System

  • Recommendation: Utilize a robust, scalable CLM system (e.g., ELK Stack, Splunk, Datadog).
  • Benefits:

* Single pane of glass for all logs.

* Powerful search and filtering capabilities.

* Scalability to handle high volumes of logs.

* Integration with alerting and visualization tools.

5.3. Log Retention Policies

  • Critical/High Severity: Retain for 90 days (or as per compliance requirements) for forensic analysis and long-term trend identification.
  • Medium/Low/Informational Severity: Retain for 30 days for debugging and short-term monitoring.
  • Archiving: Explore options for archiving older logs to cold storage for compliance or deep historical analysis, if required.

5.4. Data Security and Privacy

  • PII Masking/Redaction: Sensitive Personally Identifiable Information (PII) or confidential data must be masked or redacted before logging. This can be achieved through:

* Application-level filtering.

* Log processing pipelines (e.g., Logstash filters).

  • Access Control: Implement strict role-based access control (RBAC) to the CLM system, ensuring only authorized personnel can view error logs.
  • Encryption: Logs should be encrypted in transit and at rest.

6. Alerting and Notification Mechanisms

6.1. Alerting Rules

Alerts are triggered based on configurable rules within the CLM system or dedicated alerting platforms. Rules can be based on:

  • Severity: Any Critical error.
  • Frequency: N occurrences of a specific error code within T minutes.
  • Rate of Change: Sudden spikes in error rates for a service.
  • Specific Patterns: Keywords in error messages, specific service failures.
  • Absence of Expected Events: "Heartbeat" alerts (e.g., if a service stops logging).

6.2. Notification Channels

  • Critical Alerts: PagerDuty/Opsgenie for immediate on-call notification, SMS.
  • High Alerts: Dedicated Slack/Microsoft Teams channels, Email to relevant teams.
  • Medium Alerts: Email digests, less urgent Slack/Teams channels.
  • Low/Informational Alerts: Primarily for dashboards, optional daily/weekly summaries.

6.3. Escalation Policies

  • Tiered Escalation: If an alert is not acknowledged or resolved within a predefined timeframe, it will escalate to the next level of support or management.
  • On-Call Rotations: Integration with an on-call management system (e.g., PagerDuty) to ensure the right person is notified at the right time.

6.4. Integration with Incident Management Systems

Seamless integration with existing Incident Management Systems (e.g., Jira Service Management, ServiceNow) to automatically create incident tickets upon critical alerts, streamlining the incident response process.


7. Error Resolution Workflow and Best Practices

7.1. Incident Response Workflow

  1. Detection: Error identified via alert or dashboard.
  2. Notification: Relevant team (e.g., L1 Support, On-Call Engineer) is notified.
  3. Acknowledgement: Incident ticket created/updated, and acknowledged by the responder.
  4. Investigation:

* Review error details in the CLM system.

* Consult monitoring dashboards for related metrics.

* Reproduce the error if possible.

* Collaborate with other teams (e.g., database, network).

  1. Mitigation/Resolution:

* Apply a hotfix.

* Rollback to a previous stable version.

* Temporarily disable problematic features.

* Restart services.

* Implement permanent fix.

  1. Verification: Confirm the fix resolves the issue and no new problems are introduced.
  2. Closure: Update incident ticket with resolution details and perform a post-mortem if warranted.

7.2. Role Definitions

  • L1 Support: Initial triage, basic troubleshooting, escalation.
  • L2 Support/Operations: Deeper investigation, service restarts, data fixes, minor code changes.
  • L3 Support/Development: Root cause analysis, code fixes, system design changes.

7.3. Post-Mortem Analysis

For Critical and High-severity incidents, a post-mortem process will be initiated to:

  • Identify the root cause.
  • Document lessons learned.
  • Define preventative measures (e.g., new monitoring, code refactoring, process changes).
  • Share knowledge across teams.

7.4. Development Best Practices

  • Defensive Programming: Validate inputs, handle nulls, anticipate edge cases.
  • Meaningful Error Messages: Provide context that aids debugging, avoid exposing sensitive internal details to users.
  • Custom Exception Types: Create specific exception classes for domain-specific errors.
  • Idempotent Operations: Design systems to handle retries gracefully without adverse side effects.
  • Circuit Breakers & Retries: Implement patterns to prevent cascading failures and improve resilience against transient errors.
  • Unit & Integration Testing: Thoroughly test error paths and exception handling.

8. Monitoring, Reporting, and Analytics

8.1. Real-time Dashboards

Dedicated dashboards (e.g., in Kibana, Grafana, Datadog) providing:

  • Overall Error Rate: Total errors per minute/hour.
  • Errors by Severity: Breakdown of Critical, High, Medium errors.
  • Top N Errors: Most frequently occurring errors (by code, message, or affected service).
  • Affected Services/Components: Identify which parts of the system are experiencing issues.
  • Error Trends: Historical view of error rates to spot anomalies.
  • Mean Time To Acknowledge (MTTA) / Mean Time To Resolve (MTTR): Key operational metrics.

8.2. Automated Reporting

  • Daily/Weekly Error Summaries: Automated reports emailed to development and operations teams, highlighting key error metrics and trends.
  • Monthly Performance Reviews: In-depth analysis of error handling effectiveness, including RCA findings and improvements
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);}});}