- Solidity 教程
- Solidity - 首頁
- Solidity - 概述
- Solidity - 環境搭建
- Solidity - 基本語法
- Solidity - 第一個應用
- Solidity - 註釋
- Solidity - 資料型別
- Solidity - 變數
- Solidity - 變數作用域
- Solidity - 運算子
- Solidity - 迴圈
- Solidity - 條件判斷
- Solidity - 字串
- Solidity - 陣列
- Solidity - 列舉
- Solidity - 結構體
- Solidity - 對映
- Solidity - 型別轉換
- Solidity - 以太幣單位
- Solidity - 特殊變數
- Solidity - 風格指南
- Solidity 函式
- Solidity - 函式
- Solidity - 函式修飾符
- Solidity - View 函式
- Solidity - Pure 函式
- Solidity - 回退函式 (Fallback Function)
- 函式過載
- 數學函式
- 加密函式
- Solidity 常用模式
- Solidity - 提款模式
- Solidity - 受限訪問
- Solidity 進階
- Solidity - 合約
- Solidity - 繼承
- Solidity - 建構函式
- Solidity - 抽象合約
- Solidity - 介面
- Solidity - 庫
- Solidity - 彙編
- Solidity - 事件
- Solidity - 錯誤處理
- Solidity 有用資源
- Solidity - 快速指南
- Solidity - 有用資源
- Solidity - 討論
Solidity - 錯誤處理
Solidity 提供多種錯誤處理函式。通常情況下,當發生錯誤時,狀態會回滾到其原始狀態。其他檢查是為了防止未授權的程式碼訪問。以下是錯誤處理中的一些重要方法:
assert(bool condition) − 如果條件不滿足,此方法呼叫會導致無效操作碼,並且對狀態所做的任何更改都會回滾。此方法用於內部錯誤。
require(bool condition) − 如果條件不滿足,此方法呼叫會回滾到原始狀態。此方法用於輸入或外部元件中的錯誤。
require(bool condition, string memory message) − 如果條件不滿足,此方法呼叫會回滾到原始狀態。此方法用於輸入或外部元件中的錯誤。它提供了一個選項來提供自定義訊息。
revert() − 此方法中止執行並回滾對狀態所做的任何更改。
revert(string memory reason) − 此方法中止執行並回滾對狀態所做的任何更改。它提供了一個選項來提供自定義訊息。
示例
嘗試以下程式碼來了解 Solidity 中的錯誤處理機制。
pragma solidity ^0.5.0;
contract Vendor {
address public seller;
modifier onlySeller() {
require(
msg.sender == seller,
"Only seller can call this."
);
_;
}
function sell(uint amount) public payable onlySeller {
if (amount > msg.value / 2 ether)
revert("Not enough Ether provided.");
// Perform the sell operation.
}
}
當呼叫 revert 時,它將返回如下所示的十六進位制資料。
輸出
0x08c379a0 // Function selector for Error(string) 0x0000000000000000000000000000000000000000000000000000000000000020 // Data offset 0x000000000000000000000000000000000000000000000000000000000000001a // String length 0x4e6f7420656e6f7567682045746865722070726f76696465642e000000000000 // String data
廣告