| title | Exception Handling & Runtime Class | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| actions |
|
||||||||
| material |
|
Since any data can be passed into our method call, we want our GenerateAlien () method to be able to handle unexpected parameters, and verify that whoever is calling the contract is authorised.
Exception objects are sometimes thrown when unexpected parameters are passed into the contract. This gives developers more feedback and enables them to use try-catch statements to handle the exceptions in their code. An example of throwing an exceptions can be as follows:
throw new System.ArgumentException ("Parameter cannot be null"); Exceptions are supported in Neo contracts.
Runtime class inside the NEO smart contract framework is a very useful class for obtaining information about the contract during the current execution. We have previously used the Notify () method of the class.
It has the following attributes:
Timegets the time stamp of the current blockTriggergets the trigger type for the current contract call.
And the following methods
CheckWitness (byte[] AddrOrPubkey)checks that theAddrOrPubkeyis the address or public key of the same account that is currently calling this contract.Log (string)sends a log message to the client executing the contract.Notify (params object[])raises a notification event to the client executing the contract.
A contract on the Neo network is most often called using a Verification trigger or an Application trigger.
A Verification trigger can accept multiple parameters and return a boolean value. It is used in the network to determine whether a transaction is valid. A contract that handles these triggers may look like this:
public static bool Main (byte[] signature) {
if (Runtime.Trigger == TriggerType.Verification) {
if (/*condition*/)
return true;
else
return false;
}
}Note that TriggerType is a built-in enum type in NEO services. Verification is a field inside this enum type with value 0.
An Application trigger calls the contract as a function, can accept multiple parameters, change the state of the blockchain, and return values any type.
Since our contract is a collection of functions, we will be solely concerned with dealing with Application triggers.
- In the main method, check if runtime trigger type is 'application'. If it is, run the switch statement. If not, return false.
- In the
GenerateAlien ()method, check if variableowneris the desired length(20 or 33). If it equals to neither, raise an InvalidOperationException with the message: "The parameter owner should be a 20-byte address or a 33-byte public key" - In the same method, use
CheckWitnessto check the validity ofowner. If the check fails, return false. This ensures that the wallet that calls the method can only generate aliens for itself.