What is the behavior of Error.reject

Try to use the Error from base library.

import Error "mo:base/Error";

actor Main {
    var c = 1;

    public func add1() : async Nat {
        c += 100;
        throw Error.reject("test"); 
    };

    public func add2() : async Nat {
        c += 100;
        assert(false);
        return c;
    };

    public func reset() : async Nat {
        c := 1;
        return c;
    };

    public query func getc() : async Nat {
        return c;
    };
};

here is my log:

sudo dfx build main
Password:
Building canisters...

sudo dfx canister --no-wallet install main -m=reinstall
Reinstalling code for canister main, with canister_id rwlgt-iiaaa-aaaaa-aaaaa-cai

dfx canister --no-wallet call main getc
(1)

dfx canister --no-wallet call main add2
The Replica returned an error: code 5, message: "Canister rwlgt-iiaaa-aaaaa-aaaaa-cai trapped explicitly: assertion failed at /Users/flyq/workspace/test/pubfunc/src/main.mo:13.9-13.22"
dfx canister --no-wallet call main getc
(1)

dfx canister --no-wallet call main add1
The Replica returned an error: code 4, message: "test"

dfx canister --no-wallet call main getc
(101)

assert correctly throw an exception and successfully rolled back the state, meets expectations.

But Error.reject throws an exception, but there is no rollback state.

That is the intended semantics, not a bug.

  1. If I want to throw an exception in Motoko, I want to be guaranteed the rollback state and throw the related information of the exception, what should I need to do?
  2. Is there more information about Error.reject? I find Overview of canister calling, but not about Error.

I found a little bit of info here but I don’t think it fully answers your questions.

1 Like

An uncaught/escaping throw expression maps to the System API call msg_reject, which has the property of committing state changes, just like msg_reply. So the high-level semantics is largely determined by that of the low-level platform.

Note that throws can be locally caught using try-catch expressions, and it would be weird if those caught throws reverted state.

1 Like