observe<T> method
Future<Either<Failure, T> >
observe<T>({
- required FutureOr<
Either< task(Failure, T> >- MessageLog? messageLog
- List<
ExceptionConverter< ? exceptionConverters,Exception, T> > - 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:
- Errors are not caught by this method considering that it is bad practice to catch an Error. See https://groups.google.com/a/dartlang.org/g/misc/c/lx9CXiV3o30/m/s5l_PwpHUGAJ.
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);
}