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

As part of the "Error Handling System" workflow, this deliverable provides a comprehensive, detailed, and production-ready code implementation for a robust error handling system. This system is designed to improve the reliability, maintainability, and observability of your applications by centralizing error management, providing actionable insights, and enabling prompt responses to issues.


Project Overview: Error Handling System

This document outlines the design and provides the core code components for a sophisticated error handling system. The goal is to move beyond basic try-except blocks to a more structured, scalable, and observable approach to managing errors in your applications.

Key Objectives:

Key Principles of Robust Error Handling

Before diving into the code, it's crucial to understand the principles guiding this system:

  1. Fail Fast, Fail Loud, But Fail Gracefully: Identify errors quickly, log them comprehensively, and prevent cascading failures, but present user-friendly messages.
  2. Never Catch Exception Broadly (Unless Global Handler): Catch specific exceptions to avoid masking programming errors or unexpected behavior. The global handler is an exception to this rule, as its purpose is to catch everything that slips through.
  3. Log, Don't Print: Use a robust logging framework to capture errors with severity levels, timestamps, and contextual data.
  4. Separate Concerns: Keep error reporting, logging, and recovery logic distinct.
  5. User-Friendly Messages: Translate technical errors into understandable messages for end-users, while retaining full technical details for developers.
  6. Idempotency & Retries: Design operations to be idempotent where possible, and implement intelligent retry mechanisms for transient errors.
  7. Monitor & Alert: Integrate with monitoring tools and notification services to ensure timely awareness of critical issues.

System Architecture and Components

The proposed error handling system is built around several interconnected components, designed for modularity and extensibility.

text • 1,453 chars
**Core Components:**

1.  **Custom Exception Classes (`exceptions.py`):** Define a hierarchy of domain-specific exceptions to provide richer context than standard exceptions.
2.  **Centralized Error Logging (`error_logger.py`):** A wrapper around a standard logging library (e.g., Python's `logging` module) to ensure consistent log formatting, severity levels, and contextual data capture.
3.  **Global Exception Handler / Decorator (`error_handler.py`):**
    *   **Decorator:** A Python decorator to wrap functions and methods, automatically catching specified exceptions, logging them, and potentially performing recovery actions.
    *   **Global Handler:** A mechanism (e.g., `sys.excepthook` for general apps, middleware for web apps) to catch *any* unhandled exception that propagates up the call stack.
4.  **Error Notification Service (`notification_service.py`):** A pluggable service responsible for sending alerts to various channels (e.g., email, Slack, PagerDuty) based on error severity and configuration.
5.  **Configuration (`config.py`):** Centralized settings for logging levels, notification thresholds, and other system parameters.

## Implementation Details and Code

The following sections provide the production-ready Python code for each component, along with detailed explanations and usage examples.

---

### 1. `config.py` (Configuration)

This file centralizes all configurable parameters for the error handling system.

Sandboxed live preview

This document outlines a comprehensive and detailed study plan for developing a robust Error Handling System. This plan is designed to equip developers and architects with the knowledge and practical skills required to design, implement, and maintain resilient software systems.

Detailed Study Plan: Error Handling System

1. Introduction

Effective error handling is paramount to building reliable, maintainable, and user-friendly software. An unhandled error can lead to system crashes, data corruption, security vulnerabilities, and a poor user experience. This study plan provides a structured approach to understanding various error types, common handling patterns, language-specific best practices, and integration with essential observability tools like logging and monitoring.

The goal is not merely to catch errors, but to design systems that anticipate, gracefully recover from, and provide meaningful insights into failures, thereby enhancing overall system resilience and stability.

2. Overall Learning Objectives

Upon completion of this study plan, participants will be able to:

  • Understand Fundamental Concepts: Clearly differentiate between errors, exceptions, and various error types (e.g., expected vs. unexpected, compile-time vs. run-time).
  • Master Error Handling Patterns: Comprehend and apply common error handling patterns such as exceptions, return codes, and monadic types (Result/Either).
  • Apply Language-Specific Best Practices: Implement robust error handling strategies tailored to specific programming languages (e.g., Python, Java, Go, Rust, JavaScript).
  • Design Custom Error Hierarchies: Create meaningful and actionable custom error types that provide sufficient context for debugging and recovery.
  • Integrate with Observability: Effectively log errors with appropriate severity levels and context, and integrate with monitoring and alerting systems.
  • Test Error Handling: Develop comprehensive test cases to validate error handling logic and ensure system resilience.
  • Consider User Experience: Design error messages and recovery mechanisms that enhance the end-user experience.
  • Architect Resilient Systems: Understand advanced concepts like circuit breakers, retries, and idempotency for fault tolerance in distributed systems.

3. Target Audience

This study plan is ideal for:

  • Software Developers: Looking to deepen their understanding and practical application of error handling.
  • Software Architects: Responsible for designing resilient and fault-tolerant systems.
  • System Designers: Aiming to integrate robust error handling into overall system architecture.
  • DevOps Engineers: Seeking to understand error propagation and monitoring for operational excellence.

4. Suggested Duration

6 Weeks (approximately 10-15 hours per week, adjustable based on prior experience and learning pace).

5. Weekly Schedule

Week 1: Fundamentals of Error Handling & Types of Errors

  • Learning Objectives:

* Define errors, exceptions, and their roles in software.

* Distinguish between different categories of errors.

* Understand the impact of unhandled errors on system stability and user experience.

  • Topics:

* What is an Error vs. an Exception? (Conceptual differences, common misconceptions).

* Categories of Errors:

* Compile-time vs. Run-time errors.

* Expected (recoverable) vs. Unexpected (unrecoverable) errors.

* System errors vs. Application-specific errors.

* Logic errors (bugs) vs. Environmental errors (e.g., network, file system).

* The Cost of Poor Error Handling: Security implications, data integrity issues, operational overhead, user dissatisfaction.

* Basic Error Handling Mechanisms: Introduction to simple checks and return values.

  • Activities:

* Readings on fundamental concepts of error handling.

* Analyze case studies of real-world system failures caused by inadequate error handling.

* Identify and categorize errors in existing simple codebases.

Week 2: Common Error Handling Patterns - Part 1 (Exceptions & Return Codes)

  • Learning Objectives:

* Understand the mechanics and appropriate use cases for exceptions.

* Evaluate the pros and cons of using return codes for error signaling.

* Implement basic error handling using both patterns.

  • Topics:

* Exceptions:

* How exceptions work: Call stack unwinding, control flow disruption.

* try-catch-finally blocks: Structure and purpose.

* Checked vs. Unchecked exceptions (focus on Java as an example, discuss relevance in other languages).

* When to throw/raise an exception.

* Creating custom exception classes (basic structure).

* Return Codes/Error Values:

* Using specific function return values (e.g., null, false, special constants, errno in C).

* Pros: Explicit handling, no control flow disruption.

* Cons: Boilerplate code, easy to ignore, ambiguity.

* Error enums for clearer return codes.

  • Activities:

* Implement simple functions that can fail, using both exceptions and return codes in your preferred programming language.

* Refactor code examples to compare the verbosity and clarity of each approach.

* Discuss scenarios where one pattern is clearly superior to the other.

Week 3: Common Error Handling Patterns - Part 2 (Monadic Types & Error Propagation)

  • Learning Objectives:

* Explore functional approaches to error handling using monadic types.

* Master strategies for effective error propagation and context preservation.

* Understand the concept of unrecoverable errors and panic mechanisms.

  • Topics:

* Monadic Error Handling (e.g., Result<T, E> in Rust/Swift, Either<L, R> in functional languages):

* Concept: Encapsulating success (value) or failure (error) in a single type.

* Benefits: Type safety, forces explicit error handling, composability.

* Comparison with exceptions and return codes.

* Using pattern matching or chained operations (map, and_then) for handling.

* Error Propagation:

* When to handle an error vs. when to re-throw/propagate it up the call stack.

* Wrapping exceptions/errors to add context without losing the original cause (e.g., raise from in Python, cause in Java exceptions).

* Creating meaningful error chains.

* Panic/Crash Handling: Understanding unrecoverable states (e.g., panic! in Rust/Go, System.exit() in Java).

  • Activities:

* Study Result type in Rust or Either in a functional language (e.g., Scala, Haskell, or a library in Python/Java).

* Refactor previous week's examples using a monadic approach if applicable to your language (or simulate it).

* Practice propagating errors with added context across multiple function calls.

Week 4: Language-Specific Best Practices & Custom Errors

  • Learning Objectives:

* Deep dive into error handling idioms and best practices for specific programming languages.

* Design and implement effective custom error hierarchies.

* Learn to provide rich context within error messages and objects.

  • Topics:

* Language-Specific Guidelines & Idioms:

* Python: try-except-else-finally, raise from, custom exceptions, logging.

* Java: Checked vs. Unchecked exceptions, throws clause, Exception hierarchy, custom exceptions.

* Go: Multi-value returns (value, err), defer for cleanup, custom error types (interface error).

* JavaScript: try-catch-finally, Error objects, custom errors, Promise rejection handling (.catch(), async-await).

* Rust: Result<T, E>, Option<T>, ? operator, unwrap/expect, panic!.

* Designing Custom Error Hierarchies:

* When to create specific error types vs. reusing generic ones.

* Structuring error classes/enums for clarity and extensibility.

* Providing application-specific error codes and user-friendly messages.

* Including relevant data (e.g., input values, timestamps, correlation IDs) within error objects

python

error_logger.py

import logging

import logging.handlers

import sys

from typing import Optional, Dict, Any

from config import app_config

class ContextFilter(logging.Filter):

"""

A logging filter to inject contextual information (trace_id, user_id, request_id)

into log records.

"""

def __init__(self, name: str = ""):

super().__init__(name)

self.trace_id = None

self.user_id = None

self.request_id = None

def filter(self, record: logging.LogRecord) -> bool:

record.trace_id = self.trace_id if self.trace_id else "N/A"

record.user_id = self.user_id if self.user_id else "N/A"

record.request_id = self.request_id if self.request_id else "N/A"

return True

def set_context(self, trace_id: Optional[str] = None, user_id: Optional

gemini Output

Error Handling System: Comprehensive Review and Documentation

Project: Error Handling System

Workflow Step: 3 of 3 - Review and Documentation

Date: October 26, 2023

Prepared For: [Customer Name/Organization]


1. Executive Summary

This document provides a comprehensive overview and detailed documentation of the proposed and implemented Error Handling System. A robust error handling strategy is critical for ensuring system stability, enhancing user experience, and enabling efficient issue resolution. This system is designed to detect, classify, log, notify, and facilitate the resolution of errors across all integrated components. By standardizing error management, we aim to significantly improve system reliability, reduce downtime, and provide clear insights into operational health. This deliverable outlines the core principles, architectural components, implementation best practices, and the tangible benefits of this system.

2. Core Principles of the Error Handling System

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

  • Robustness & Resilience: Design for failure, ensuring the system can gracefully handle unexpected events without crashing or corrupting data.
  • User Experience Focus: Minimize impact on end-users by providing clear, helpful messages and enabling graceful degradation where possible. Avoid exposing technical details to users.
  • Diagnosability & Observability: Provide sufficient context and logging to quickly identify the root cause of errors. Integrate with monitoring and alerting tools.
  • Proactivity & Alerting: Detect critical issues early and notify relevant stakeholders immediately to prevent wider impact.
  • Consistency & Standardization: Employ uniform error codes, messages, and logging formats across all services and components for easier interpretation and automation.
  • Security: Ensure error messages do not expose sensitive information (e.g., database connection strings, internal API keys) to unauthorized parties.
  • Traceability: Allow for end-to-end tracing of requests and errors, linking related events across distributed systems.

3. System Architecture and Components

The Error Handling System is composed of several interconnected components, working in unison to manage errors effectively:

3.1. Error Detection Mechanisms

  • Code-Level Exception Handling:

* try-catch-finally blocks for synchronous operations.

* Asynchronous error handling (e.g., promise rejections, async/await error propagation).

* Specific exception types for different error categories (e.g., ValidationException, NotFoundException, ServiceUnavailableException).

  • Input Validation:

* Schema validation (e.g., JSON Schema, OpenAPI/Swagger validation).

* Business rule validation at API gateways and service layers.

  • API Response Checks:

* HTTP status code verification for external service calls (e.g., 2xx for success, 4xx for client errors, 5xx for server errors).

* Payload validation for expected data structures and content.

  • Database Error Handling:

* Catching database-specific exceptions (e.g., connection errors, constraint violations).

* Transaction management with rollback on failure.

  • External Service Integration:

* Implementing timeouts, retries (with backoff), and circuit breakers for unreliable external dependencies.

3.2. Error Classification

Errors are systematically classified to aid in prioritization, routing, and analysis:

  • User Errors (4xx Client Errors):

* Validation Errors: Invalid input format, missing required fields.

* Authorization/Authentication Errors: Access denied, invalid credentials.

* Resource Not Found: Request for a non-existent resource.

* Conflict: Attempt to create a duplicate resource or violate a unique constraint.

  • System Errors (5xx Server Errors):

* Internal Server Error: Unhandled exceptions, unexpected logic failures.

* Service Unavailable: Dependencies are down, resource exhaustion.

* Gateway Timeout: Upstream service did not respond in time.

* Bad Gateway: Invalid response from an upstream server.

  • External Service Errors: Failures originating from third-party APIs or external systems.
  • Infrastructure Errors: Issues related to networking, hardware, or cloud provider services.

3.3. Error Logging and Monitoring

  • Centralized Logging System:

* Utilizing a robust logging framework (e.g., ELK Stack - Elasticsearch, Logstash, Kibana; Splunk; Datadog Logs; AWS CloudWatch Logs).

* Structured logging (JSON format) to ensure parseability and queryability.

* Inclusion of essential metadata: timestamp, service name, environment, log level, request ID, user ID (if applicable), error code, error message, stack trace.

  • Metrics and Dashboards:

* Monitoring key error metrics: error rate (errors/requests), unique error count, latency of error responses.

* Configuring custom dashboards (e.g., Grafana, Datadog Dashboards, CloudWatch Dashboards) to visualize error trends and anomalies.

* Tracking specific error types and their frequency over time.

3.4. Error Notification and Alerting

  • Critical Error Alerts:

* Immediate notification for high-severity errors (e.g., system crashes, high error rates, critical service unavailability).

* Integration with on-call rotation systems (e.g., PagerDuty, Opsgenie) for critical alerts.

* Communication channels: Slack/Teams channels, email, SMS.

  • Threshold-Based Alerts:

* Alerts triggered when error rates exceed predefined thresholds for a specific service or endpoint.

* Alerts for specific error codes or patterns appearing with unusual frequency.

  • Informational Notifications:

* Summary reports or daily digests for less critical, but still important, error trends.

3.5. Error Reporting and Analytics

  • Error Tracking Tools:

* Integration with dedicated error tracking platforms (e.g., Sentry, Bugsnag, Rollbar) for de-duplication, context enrichment, and issue management.

* Ability to group similar errors, assign ownership, and track resolution status.

  • Root Cause Analysis (RCA) Support:

* Providing tools and data to facilitate deep dives into error causes, including log correlation, performance metrics, and application traces.

  • Trend Analysis:

* Identifying recurring error patterns, performance bottlenecks, or areas requiring refactoring based on aggregated error data.

3.6. Error Resolution Workflow

  • Incident Management Integration:

* Seamless integration with incident management platforms (e.g., Jira Service Management, ServiceNow) for creating, tracking, and resolving error-related incidents.

* Automated ticket creation for critical alerts.

  • Runbooks and Documentation:

* Maintaining clear runbooks for common error scenarios, outlining diagnostic steps and resolution procedures.

* Knowledge base for frequently encountered errors and their solutions.

  • Post-Mortem Process:

* Structured post-mortem analysis for significant incidents to document lessons learned and implement preventive measures.

3.7. User Feedback and Graceful Degradation

  • Meaningful User Messages:

* Translating technical errors into user-friendly messages that explain the situation and suggest next steps (e.g., "Please try again later," "Contact support with reference ID X").

  • Fallback Mechanisms:

* Implementing fallback logic (e.g., returning cached data, default values) when critical services are unavailable.

  • Retry Mechanisms:

* Automatic retries for transient errors (e.g., network glitches) with exponential backoff.

4. Implementation Details and Best Practices

To ensure the effectiveness and maintainability of the Error Handling System, the following best practices are adopted:

  • Standardized Error Codes and Messages:

* Define a consistent set of application-specific error codes (e.g., APP-AUTH-001, APP-VALID-002) in addition to HTTP status codes.

* Maintain a central registry or documentation for all error codes and their corresponding user-facing and internal messages.

  • Contextual Information in Logs:

* Always include a unique correlationId (or requestId) for each incoming request to trace its journey across microservices.

* Log relevant business context (e.g., userId, orderId, transactionId) to aid in debugging.

* Capture full stack traces for exceptions, but ensure they are not exposed to end-users or external systems.

  • Idempotency and Retries:

* Design APIs to be idempotent where possible, allowing safe retries without unintended side effects.

* Implement client-side retry logic with exponential backoff and jitter to prevent thundering herd problems.

  • Circuit Breakers and Bulkheads:

* Utilize circuit breaker patterns to prevent cascading failures when a downstream service becomes unresponsive.

* Implement bulkheads to isolate components and prevent a failure in one from affecting the entire system.

  • Testing Error Paths:

* Write unit, integration, and end-to-end tests specifically for error scenarios (e.g., invalid input, service unavailability, network timeouts).

* Conduct chaos engineering experiments to proactively identify weaknesses in error handling.

  • Documentation:

* Maintain up-to-date documentation for the error handling framework, including guidelines for developers, a list of error codes, and instructions for debugging.

  • Security Considerations:

* Sanitize all error messages before displaying them to users or logging them in publicly accessible systems.

* Avoid logging sensitive data (e.g., PII, passwords, API keys) in plain text.

* Ensure proper access controls are in place for log aggregation and monitoring systems.

5. Benefits of a Robust Error Handling System

Implementing and adhering to this comprehensive Error Handling System provides significant benefits:

  • Improved System Stability and Reliability: Proactive detection and management of errors lead to fewer outages and more resilient services.
  • Enhanced User Experience: Clear, helpful error messages and graceful degradation reduce user frustration and maintain trust.
  • Faster Issue Resolution: Detailed logs, centralized monitoring, and automated alerts enable operations and development teams to diagnose and resolve issues more quickly.
  • Better System Visibility and Insights: Aggregated error data provides valuable insights into system health, performance bottlenecks, and areas for improvement.
  • Reduced Operational Overhead: Automation of alerting and incident creation reduces manual intervention and streamlines incident management.
  • Increased Developer Productivity: Standardized error handling patterns reduce cognitive load for developers and simplify debugging.
  • Compliance and Audit Readiness: Well-documented error handling processes contribute to meeting regulatory and compliance requirements.

6. Next Steps and Recommendations

To fully leverage the capabilities of this Error Handling System, we recommend the following actions:

  1. Deployment Plan: Finalize the phased rollout plan for integrating the error handling framework across all services and applications, prioritizing critical paths.
  2. Developer Training & Workshops: Conduct mandatory training sessions for all development teams on the use of the error handling framework, best practices, and logging standards.
  3. Documentation Dissemination: Ensure all relevant documentation (developer guidelines, error code registry, runbooks) is easily accessible and regularly updated.
  4. Monitoring & Alerting Configuration Review: Regularly review and fine-tune monitoring dashboards and alert thresholds to minimize false positives and ensure critical issues are captured.
  5. Pilot Program: Implement the full system in a non-critical service or environment first to gather feedback and refine the process before wider adoption.
  6. Continuous Improvement: Establish a feedback loop for developers and operations teams to suggest improvements to the error handling system and processes.
  7. Security Audit: Conduct a dedicated security audit of the error handling system to ensure no sensitive information is inadvertently exposed.

7. Conclusion

The "Error Handling System" is a foundational pillar for building and maintaining reliable, high-performing applications. By meticulously designing, implementing, and documenting this system, we are empowering our teams with the tools and processes necessary to deliver a superior product experience and ensure operational excellence. This comprehensive approach will significantly enhance our ability to manage unforeseen challenges, maintain system integrity, and continuously improve our services.

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);}});}