Error
Errorハンドリングについて学習します
Solidityでは例外・条件の検証で異常が見つかった場合に処理を停止させる機構があります
これにより不正な値の変更などを防ぐことができます
assert
assert(condition);
で呼び出す
conditionがfalseの場合、Panicを発し、実行前の状態に戻し、ガスをすべて消費する
基本的にオーバーフローなどsolidity自体の例外が発生した場合に用いられる
require
require(condition);
require(condition,"error message");
で呼び出す
conditionがfalseの場合、Errorを発し、実行前の状態に戻し、残ったガスを返す
コントラクトに期待した制約が満たされているかを確認するために用いられる
revert
revert();
revert("error message");
で呼び出す
到達した時点で実行前の状態に戻し、残ったガスを返す
require(false);とif (true) revert();は等価である
custom error
revertにおけるエラーをメッセージではなくエラーの種類で表現するために用いられる
宣言
contract CustomError {
error identifier();
}
で宣言する
呼び出し
contract CustomError {
error Unauthorized();
function revertFunction() {
revert Unauthorized();
}
}
で呼び出す
try-catch
例外をキャッチして処理を進める場合に用いる externalな関数またはコントラクトの生成のみ使える
try contract.externalFunction() returns (uint v) {
} catch Error(string memory /*reason*/) {
// This is executed in case of a revert or require
} catch Panic(uint /*errorCode*/) {
// This is executed in case of a assert
} catch (bytes memory /*lowLevelData*/) {
// This is executed in case any other clause
} catch {
// This is executed in case no interest in the error data
}