Weird array out of bounds error

function initializeDirectCanDBPartitionClient(canisterId: Principal)
{
  const host = isLocal ? "http://127.0.0.1:8000" : "https://ic0.app";
  const agent = new HttpAgent({ host });
  return Actor.createActor(CanDBPartitionIDL, { agent, canisterId });
};
...
const client = initializeDirectCanDBPartitionClient(obj.itemRef.canister);
obj.item = await client.getItem(BigInt(obj.itemRef.id)) as any;

produces

Uncaught (in promise) Error: Call failed:
  Canister: a3shf-5eaaa-aaaaa-qaafa-cai
  Method: getItem (query)
  "Status": "rejected"
  "Code": "CanisterError"
  "Message": "IC0503: Canister a3shf-5eaaa-aaaaa-qaafa-cai trapped explicitly: Array index out of bounds"
    at caller (index.js:184:27)
    at async ItemData.create (index.js:78705:20)

But

  func _getAttribute(options: CanDB.GetOptions, subkey: Text): ?Entity.AttributeValue {
    Debug.print("ITEM-1: "); // FIXME: Remove.
    let all = CanDB.get(db, options);
    Debug.print("ITEM0: " # debug_show(all)); // FIXME: Remove.
    do ? { RBT.get(all!.attributes, Text.compare, subkey)! };
  };
...
  public query func getItem(itemId: Nat): async ?lib.Item {
    let data = _getAttribute({sk = "i/" # Nat.toText(itemId)}, "i");
    Debug.print("ITEM: " # debug_show(data)); // FIXME: Remove.
    do ? { lib.deserializeItem(data!) };
  };

should output at least ITEM-1:, which however does not appear in the logs of dfx start.

Why the error?!

I changed the Motoko code to:

  public query func getItem(itemId: Nat): async ?lib.Item {
    Debug.print("ITEMXXX");
    return null; // to ensure the action is completely done
    let data = _getAttribute({sk = "i/" # Nat.toText(itemId)}, "i");
    Debug.print("ITEM: " # debug_show(data));
    do ? { lib.deserializeItem(data!) };
  };

in order to be sure Debug.print is not prevented to work by rollback.

But I have still no messages output. Help!

It seems, that the error is explainable by canister ID being missing in .env file, what is in turn explainable by a canister missing in dfx.json dependencies of the canister that was last deployed.

You should probably ask in CanDB discord server CanScale
@icme

Array index out of bounds is thrown when you have something like - array with 10 elements:
let myArr = Array.init(10, null)

and then you try to access myArr[50]

The code you are showing has nothing to do with the error. It’s somewhere deep below. Your CanDB setup is probably wrong.

1 Like