Error Handling and Logging
Relevant source files
The following files were used as context for generating this wiki page:The Sovereign Communications (SC) project implements a multi-layered, comprehensive system for error handling, logging, and monitoring. This system is designed to capture, categorize, and process errors from both the core library (@sc/core) and the client-side applications. It includes a centralized error handler, structured error objects, local and remote logging capabilities, integration with third-party monitoring services like Sentry, and automatic recovery mechanisms for specific error types.
The architecture separates concerns, with a core framework for handling all errors, a dedicated logging utility, a serverless function for remote log aggregation, and specific UI components like React Error Boundaries to manage view-layer exceptions gracefully. This ensures that errors are not only caught but also provide rich context for debugging, monitoring, and improving application stability.
Core Error Handling Framework
The heart of the system resides in the @sc/core library, providing a standardized way to create, handle, and analyze errors throughout the application. It is built around the ErrorHandler singleton and structured AppError objects.
Sources: core/src/error-handler.ts, core/src/error-handling.ts
Error Structure
Errors are encapsulated in custom classes (AppError or SCError) that extend the native Error object. This provides a consistent structure with detailed context for every error.
Error Categories and Severities
Errors are classified by ErrorCategory and ErrorSeverity to enable targeted handling and reporting.
Category (ErrorCategory) | Description |
|---|---|
NETWORK | Network-related issues like connection failures. |
CRYPTO | Cryptographic errors, such as encryption or signature failure. |
STORAGE | Issues with data persistence (e.g., IndexedDB). |
VALIDATION / PROTOCOL | Data format or protocol validation errors. |
PERMISSION | Missing permissions for device resources (e.g., camera, BLE). |
SYSTEM / UNKNOWN | Uncategorized or general system errors. |
BLE | Bluetooth Low Energy specific errors. |
WEBRTC | WebRTC connection errors. |
UI | User interface-related errors. |
Severity (ErrorSeverity) | Description | Console Method |
|---|---|---|
LOW | Minor issues, informational. | console.log |
MEDIUM | Non-critical problems that should be noted. | console.warn |
HIGH | Significant issues that may impact functionality. | console.error |
CRITICAL | Severe errors that may compromise security or cause data loss. | console.error |
Sources: core/src/error-handler.ts:10-25, core/src/error-handling.ts:5-19, core/src/error-handler.ts:133-144
AppError and SCError Classes
The AppError and SCError classes provide a structured format for all application errors, containing more information than a standard Error.
The diagram below shows the structure of the core error handling classes.
ErrorHandler Singleton
The ErrorHandler is a singleton class responsible for centralizing all error processing. It can be accessed globally via ErrorHandler.getInstance() or the exported errorHandler constant.
Key responsibilities include:
- Converting standard
Errorobjects into structuredAppErrorinstances. - Logging errors to an internal, size-limited buffer (
maxLogSize: 1000). - Notifying registered listeners about new errors.
- Attempting automatic recovery for certain error categories.
- Reporting errors to external monitoring services in production.
Sources: core/src/error-handler.ts:58-70, core/src/error-handler.test.ts:100-103
The following diagram illustrates the flow of the handle method.
Automatic Recovery
The ErrorHandler includes logic to attempt automatic recovery for specific, non-critical errors.
- Network Errors: For non-critical network errors, it logs a message indicating it will queue the operation for a retry.
- Storage Errors: If a
QUOTA_EXCEEDEDerror occurs, it warns the user and can trigger a storage cleanup process. - Crypto Errors: Critical crypto errors trigger a severe warning, as they may indicate a security compromise.
Sources: core/src/error-handler.ts:149-181
Logging System
The project features a dual logging strategy: a flexible client-side logger for development and a remote logging endpoint for production monitoring.
Client-Side Logger
The Logger class in @sc/core provides a structured logging interface with multiple levels and contextual metadata.
- Log Levels:
DEBUG,INFO,WARN,ERROR. - Buffering: It can buffer log entries before a remote logging transport is available.
- Remote Transport: It supports a
setRemoteTransportmethod to send logs to a remote endpoint, like the Netlify function. - Global Handlers: It captures global
console.log,console.warn, etc., to centralize all output.
Sources: core/src/logger.ts
Remote Logging Endpoint
A Netlify serverless function at netlify/functions/log.ts serves as a simple remote log aggregator.
- Endpoint:
/.netlify/functions/log - Method:
POST - Body: Expects a JSON payload with a
logsarray. - Functionality: It receives log batches from clients and prints them to the server-side console. This is a basic mechanism for collecting client logs in a centralized place without a full-fledged logging service.
The sequence diagram below shows how a client sends logs to the Netlify function.
Frontend Error Management
The web application uses specific tools to handle errors gracefully at the UI layer and report them for analysis.
Sentry Integration
Sentry is used for production error tracking. The setup is managed in web/sentry.ts and abstracted by the ErrorTracker class.
- Initialization: Sentry is initialized with a DSN from environment variables. It is only active in the production environment.
- Sampling: Trace sampling is set to
0.1in production to manage volume. - Data Scrubbing: A
beforeSendhook is configured to remove potentially sensitive data like cookies and headers from error reports. ErrorTrackerClass: This wrapper class incore/src/error-tracking.tsprovides static methods (captureError,captureMessage,setUser) to interact with Sentry, decoupling the core logic from the Sentry SDK.
Sources: web/sentry.ts:10-27, core/src/error-tracking.ts, V1_PRODUCTION_IMPLEMENTATION_PLAN.md
React ErrorBoundary
The ErrorBoundary is a standard React component that catches JavaScript errors anywhere in its child component tree.
- Functionality: It uses the
componentDidCatchlifecycle method to intercept errors during rendering. - User Feedback: When an error is caught, it displays a fallback UI to the user, preventing a white screen of death. The UI includes an error message and a "Try again" button that attempts to recover by reloading the page.
- Reporting: Crucially, it reports the caught error and associated info to Sentry using
Sentry.captureException.
This diagram shows the ErrorBoundary workflow.
Sources: web/src/components/ErrorBoundary.tsx
Conclusion
The error handling and logging system in Sovereign Communications is robust and well-architected. It provides structured, contextual errors through the AppError class and centralizes their processing in the ErrorHandler singleton. This core framework is complemented by a versatile Logger, a remote logging endpoint, and production-grade monitoring via Sentry. On the frontend, the ErrorBoundary component ensures a good user experience even when things go wrong. This comprehensive approach is critical for maintaining application health, debugging issues efficiently, and ensuring overall system reliability.