d4t_formulas/lib/error_handler.dart

56 lines
1.5 KiB
Dart
Raw Permalink Normal View History

2026-02-09 15:57:53 +00:00
/// Centralized error handler that gets notified of every caught exception
class ErrorHandler {
/// Singleton instance of ErrorHandler
static final ErrorHandler _instance = ErrorHandler._internal();
factory ErrorHandler() => _instance;
ErrorHandler._internal();
/// Callback function to handle errors - can be overridden for custom behavior
void Function(Object error, [StackTrace? stackTrace])? onError;
2026-03-10 15:47:03 +00:00
// TODO: SET A DEFAULT ONERROR LIKE
// ScaffoldMessenger.of(context).showSnackBar(
// SnackBar(
// content: Text('Error creating derived formula: $e'),
// duration: const Duration(seconds: 3),
// ),
// );
// }
2026-02-09 15:57:53 +00:00
/// Notifies the error handler of an exception
void notify(Object error, [StackTrace? stackTrace]) {
// Print the exception to stdout as requested
print('ErrorHandler caught exception:');
print(error);
2026-02-09 16:10:47 +00:00
2026-02-09 15:57:53 +00:00
if (stackTrace != null) {
print('Stack trace:');
print(stackTrace);
}
2026-02-09 16:10:47 +00:00
2026-02-09 15:57:53 +00:00
// Call the custom error handler if provided
onError?.call(error, stackTrace);
}
2026-02-09 16:10:47 +00:00
/// Convenience method to wrap code that might throw exceptions
T handleError<T>(T Function() operation, {T? defaultValue}) {
try {
return operation();
} catch (error, stackTrace) {
notify(error, stackTrace);
if (defaultValue != null) {
return defaultValue;
}
rethrow;
}
}
2026-02-09 15:57:53 +00:00
}
/// Global instance of ErrorHandler for easy access
2026-02-09 16:01:00 +00:00
final ErrorHandler errorHandler = ErrorHandler();