handleDefault<T> method

  1. @override
Future<Either<Failure, T>> handleDefault<T>(
  1. Future<Either<Failure, T>> callback(
    1. Left<Failure, T> left(
      1. Failure failure
      ),
    2. Right<Failure, T> right(
      1. T result
      )
    ), {
  2. Either<Failure, T>? onError(
    1. Object error,
    2. Left<Failure, T> left(
      1. Failure failure
      ),
    3. Right<Failure, T> right(
      1. T response
      ),
    4. StackTrace stackTrace,
    )?,
})
inherited

Provides you with an easy way to handle common service logic This helper will help you with some boilerplate needed when implementing handling of async service logic following our architecture

callback pass your function and perform you required logic, if an exception arise, let the function handle for you or implement you custom handle with onError callback

onError can be provided to handle a specific exception on your repo/service, if you return null, it will be interpreted as not handled and the function will proceed to handle it itself

Implementation

@override
Future<Either<Failure, T>> handleDefault<T>(
  Future<Either<Failure, T>> Function(
    Left<Failure, T> Function(Failure failure) left,
    Right<Failure, T> Function(T result) right,
  ) callback, {
  Either<Failure, T>? Function(Object error, Left<Failure, T> Function(Failure failure) left,
          Right<Failure, T> Function(T response) right, StackTrace stackTrace)?
      onError,
}) async {
  failureCbk(Failure failure) {
    return Left<Failure, T>(failure);
  }

  rightCbk(T result) {
    return Right<Failure, T>(result);
  }

  try {
    try {
      final response = await callback(failureCbk, rightCbk);
      return response;
    } catch (error, stackTrace) {
      // check if user have a specific handler for this exception
      final Either<Failure, T>? handle = onError?.call(error, failureCbk, rightCbk, stackTrace);
      if (handle != null) {
        return handle;
      }
      logger.t("Error not handled by user, so handling by default logic");
      // if it was not handled then rethrow so we handle it ourselves
      rethrow;
    }
  } on ServerException catch (error, stackTrace) {
    logger.e("ServerFailure", error: error, stackTrace: stackTrace);
    return left<Failure, T>(
      ServerFailure.fromServerException(error),
    );
  } on SocketException catch (error, stackTrace) {
    logger.e("InternetConnectionIssueFailure", error: error, stackTrace: stackTrace);
    return left<Failure, T>(
      InternetConnectionIssueFailure.fromSocketException(error),
    );
  } catch (error, stackTrace) {
    logger.e("UnknownFailure", error: error, stackTrace: stackTrace);
    return left<Failure, T>(UnknownFailure.fromException(error));
  }
}