2024-01-05 07:20:55 +02:00
|
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
|
|
|
import 'package:logging/logging.dart';
|
|
|
|
|
|
|
|
typedef AsyncFuture<T> = Future<AsyncValue<T>>;
|
|
|
|
|
|
|
|
mixin ErrorLoggerMixin {
|
|
|
|
abstract final Logger logger;
|
|
|
|
|
|
|
|
/// Returns an AsyncValue<T> if the future is successfully executed
|
|
|
|
/// Else, logs the error to the overrided logger and returns an AsyncError<>
|
|
|
|
AsyncFuture<T> guardError<T>(
|
|
|
|
Future<T> Function() fn, {
|
2024-02-24 05:38:57 +02:00
|
|
|
required String errorMessage,
|
2024-01-05 07:20:55 +02:00
|
|
|
Level logLevel = Level.SEVERE,
|
|
|
|
}) async {
|
|
|
|
try {
|
|
|
|
final result = await fn();
|
|
|
|
return AsyncData(result);
|
|
|
|
} catch (error, stackTrace) {
|
2024-02-24 05:38:57 +02:00
|
|
|
logger.log(logLevel, errorMessage, error, stackTrace);
|
2024-01-05 07:20:55 +02:00
|
|
|
return AsyncError(error, stackTrace);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the result of the future if success
|
|
|
|
/// Else, logs the error and returns the default value
|
|
|
|
Future<T> logError<T>(
|
|
|
|
Future<T> Function() fn, {
|
|
|
|
required T defaultValue,
|
2024-02-24 05:38:57 +02:00
|
|
|
required String errorMessage,
|
2024-01-05 07:20:55 +02:00
|
|
|
Level logLevel = Level.SEVERE,
|
|
|
|
}) async {
|
|
|
|
try {
|
|
|
|
return await fn();
|
|
|
|
} catch (error, stackTrace) {
|
2024-02-24 05:38:57 +02:00
|
|
|
logger.log(logLevel, errorMessage, error, stackTrace);
|
2024-01-05 07:20:55 +02:00
|
|
|
}
|
|
|
|
return defaultValue;
|
|
|
|
}
|
|
|
|
}
|