Error utilities
Error utilities provide a sophisticated system for managing errors within your application. Using TypeScript interfaces and types, they provide a structured approach to recording, accessing, and logging errors.
Key features
ErrorMap<TErrorDetailMap>
Interface: Outlines the structure for an error map, including methods for setting, getting, and managing errors, alongside properties for accessing the last error and a consolidated error message string.DefaultErrorMap<TErrorDetailMap>
Class: Implements theErrorMap
interface, providing concrete logic for error management, including observable properties for reactive UI updates.
Examples
Creating an error map
Use the createErrorMap
factory function to instantiate an ErrorMap
with a custom logger function. This logger is invoked whenever an error is set, allowing for flexible error reporting.
import { createErrorMap } from '@genesislcap/foundation-utils';
const logger = (key, error) => console.error(`Error [${key}]:`, error.message);
const errorMap = createErrorMap(logger);
Recording an error
Add errors to the map using the set
method. This records the error under the specified key and updates the lastError
observable property.
errorMap.set('networkError', new Error('Failed to fetch data'));
Accessing errors
Retrieve specific errors by key, check for their presence, or get all errors as an iterable collection using get
, has
, and values
methods, respectively.
if (errorMap.has('networkError')) {
const networkError = errorMap.get('networkError');
console.log(networkError.message);
}
for (const error of errorMap.values()) {
console.warn(error.message);
}
Managing errors
Errors can be individually removed or the entire map can be cleared. The lastError
is also managed accordingly.
errorMap.delete('networkError'); // Remove a specific error
errorMap.clear(); // Clear all errors
Error messages
The messages
property provides a concatenated string of all error messages, prefaced by the total error count. This is useful for displaying error summaries to the user.
console.log(errorMap.messages); // Outputs formatted error messages
Considerations
- Use the
ErrorMap
to centralize error handling and reporting in your application. - Use the
lastError
andmessages
for user-facing error feedback, ensuring a comprehensive overview of current issues. - Employ the provided logger function to integrate with existing logging frameworks or error tracking services, enhancing observability.