Error Handling and Logging
Relevant source files
The following files were used as context for generating this wiki page:The ElmecV2 application incorporates a robust and centralized system for error handling and logging, designed to capture, categorize, and manage exceptions and application events effectively. This system is crucial for debugging during development, monitoring application health in production, and providing clear feedback to users.
The core of this system is built around two main utility classes: ErrorHandler and Logger. ErrorHandler is responsible for identifying, classifying, and processing errors from various sources like Supabase, authentication, and network requests. The Logger class provides a multi-level logging mechanism to record events, which can be directed to the console for development or a remote endpoint for production analysis. Together, they ensure that errors are not only caught but also logged with appropriate context and severity.
Sources: README.md, utils/errorHandler.ts, utils/logger.ts
Architecture Overview
The system is composed of two main static classes, ErrorHandler and Logger, which work in tandem. Errors are typically caught and processed by ErrorHandler, which standardizes them into an AppError object. This object is then passed to the Logger to be recorded. The withErrorHandling higher-order component provides a convenient way to wrap asynchronous functions, automating this entire process.
This diagram shows the general flow from an error occurring to it being logged.
Sources: utils/errorHandler.ts, utils/logger.ts
ErrorHandler
The ErrorHandler class is the central point for processing all application errors. It provides static methods to handle specific error types, categorize them, and prepare them for logging or user display.
Sources: utils/errorHandler.ts
Key Data Structures
The error handling system uses several key enums and interfaces to structure error information.
This class diagram illustrates the relationship between the ErrorHandler and its associated data structures.
Sources: utils/errorHandler.ts:4-40
ErrorSeverity Enum
Defines the impact level of an error.
| Level | Description |
|---|---|
LOW | Minor issue, does not significantly impact functionality. |
MEDIUM | Affects functionality but may have a workaround. |
HIGH | Major functionality is impaired. |
CRITICAL | System-critical failure, application may be unstable. |
| Sources: utils/errorHandler.ts:4-9 |
ErrorCategory Enum
Classifies errors based on their origin.
| Category | Description |
|---|---|
AUTH | Authentication-related errors (e.g., invalid credentials). |
NETWORK | Network connectivity issues. |
DATABASE | Errors originating from the database (e.g., Supabase). |
VALIDATION | User input or data validation failures. |
PERMISSION | Action denied due to insufficient permissions. |
UNKNOWN | Uncategorized or unexpected errors. |
| Sources: utils/errorHandler.ts:12-20 |
Error Handling Methods
ErrorHandler provides specialized methods for common error sources.
handleSupabaseError(error: any): Translates Supabase-specific error codes (e.g.,PGRST116,23505) into standardizedAppErrorobjects.handleAuthError(error: any): Handles authentication errors, such as 'Invalid login credentials' or 'Email not confirmed'.handleNetworkError(error: any): Detects network issues, including offline status vianavigator.onLine.
The handler for Supabase errors specifically maps database codes to user-friendly messages and appropriate severities.
| Supabase Code | AppError Code | Category | Severity | User Message |
|---|---|---|---|---|
42P17 | RLS_RECURSION | DATABASE | CRITICAL | Error interno del sistema. Por favor contacta soporte. |
PGRST116 | NOT_FOUND | DATABASE | LOW | El recurso solicitado no existe. |
23505 | DUPLICATE_KEY | VALIDATION | MEDIUM | Ya existe un registro con esos datos. |
23503 | FOREIGN_KEY_VIOLATION | DATABASE | HIGH | Error en la integridad de los datos. |
| Sources: utils/errorHandler.ts:51-115, REPORTE-EJECUCION-PRUEBAS.md |
withErrorHandling HOC
This higher-order component is a wrapper for asynchronous functions. It provides a try...catch block to automatically capture, handle, log, and display errors.
This sequence diagram shows how withErrorHandling intercepts and processes an error.
Sources: utils/errorHandler.ts:348-406
Logger
The Logger class is a static utility for creating, managing, and dispatching log entries. It supports different log levels, console output, and remote logging, configurable based on the application environment.
Sources: utils/logger.ts
Key Data Structures
LoggerConfig Interface
Defines the configuration options for the Logger.
| Property | Type | Default (Dev) | Default (Prod) | Description |
|---|---|---|---|---|
enableConsoleLogging | boolean | true | false | Toggles logging to the browser/device console. |
enableRemoteLogging | boolean | false | true | Toggles sending logs to a remote endpoint. |
logLevel | LogLevel | DEBUG | WARN | Minimum level of logs to process. |
maxLocalLogs | number | 1000 | 1000 | Maximum number of log entries to store in memory. |
remoteEndpoint | string | undefined | undefined | The URL for the remote logging service. |
| Sources: utils/logger.ts:4-10, 24-29 |
LogLevel Enum
Defines the severity levels for log entries.
| Level | Value |
|---|---|
DEBUG | 0 |
INFO | 1 |
WARN | 2 |
ERROR | 3 |
FATAL | 4 |
| Sources: utils/logger.ts:12-19 |
Logging Flow
The private log method is the core of the Logger. It orchestrates the entire logging process based on the current configuration.
This flowchart illustrates the logic inside the Logger.log() method.
Sources: utils/logger.ts:60-84
Specialized Logging Methods
In addition to standard level-based logging, the Logger provides methods for specific contexts, which improves log searchability and context.
logAppError(error: AppError, context?: string): Integrates withErrorHandlerby converting anAppError's severity into aLogLeveland logging it.startTimer(name: string): A performance utility that returns a function to log the elapsed time.logUserAction(action: string, ...): Logs user interactions.logApiCall(method: string, url: string, ...): Logs API requests, automatically setting the level toERRORfor status codes >= 400.
Sources: utils/logger.ts:188-238
Practical Application for Debugging
During development and debugging, detailed logging is crucial. As seen in project documentation, logging was enhanced to resolve issues, such as a non-responsive button in the requests module.
// Example of enhanced logging added for debugging
console.log('=== INICIANDO CREACIÓN DE SOLICITUD ===');
console.log('Estado del formulario:', {
titulo: newRequest.titulo,
mensaje: newRequest.mensaje?.substring(0, 50),
// ... other fields
});
This practice provides clear, step-by-step visibility into a function's execution flow, which is invaluable for identifying where a process fails.
Sources: FIXES-APLICADOS.md, TEST_REPORT.md
Conclusion
The error handling and logging system in ElmecV2 is a well-structured and essential feature for maintaining application stability and quality. By separating error handling (ErrorHandler) from event recording (Logger) and providing high-level abstractions like withErrorHandling, the system is both powerful and easy to use. Its environment-aware configuration ensures that development builds are verbose for easy debugging, while production builds are optimized to capture only critical information, aiding in post-launch monitoring and maintenance.
Sources: utils/errorHandler.ts, utils/logger.ts, README.md