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.