observe<T> method

Future<Either<Failure, T>> observe<T>({
  1. required FutureOr<Either<Failure, T>> task(
    1. MessageLog? messageLog
    ),
  2. List<ExceptionConverter<Exception, T>>? exceptionConverters,
  3. MessageLog? messageLog,
})

Converts any uncaught Exception thrown by the task into a Failure.

A messageLog can be provided to log the result of the task.

If no error occurs, then value T is returned and logger.info(messageLog) is called.

If a Failure is returned by the task, then logger.warn() is called.

If an Exception is thrown, then it is handled by the exceptionConverters and ExceptionConverterSuite.exceptionConverters.

If the Exception does not have an exception converter, then it will be converted to Failure by default using the FallbackExceptionConverter.

NOTE:

Implementation

Future<Either<Failure, T>> observe<T>({
  required FutureOr<Either<Failure, T>> Function(MessageLog? messageLog) task,
  List<ExceptionConverter<Exception, T>>? exceptionConverters,
  MessageLog? messageLog,
}) async {
  final extendedExceptionConverters =
      _extendedExceptionConverters<T>(exceptionConverters);

  return extendedExceptionConverters
      .fold<FutureOr<Either<Failure, T>> Function(MessageLog? messageLog)>(
    (messageLog) async {
      final result = await task(messageLog);

      if (messageLog != null) {
        result.fold(
          (l) => logger.warn(messageLog),
          (r) => logger.info(messageLog),
        );
      }

      return result;
    },
    (previousValue, element) => (messageLog) => element.observe(
          task: previousValue,
          logger: logger,
          messageLog: messageLog,
        ),
  )(messageLog);
}