WTF-Solidity
WTF-Solidity copied to clipboard
第30讲: try-catch中Error(string memory reason)的捕获
教程里面的描述
try externalContract.f() returns(returnType){ // call成功的情况下 运行一些代码 } catch Error(string memory reason) { // 捕获失败的 revert() 和 require() } catch (bytes memory reason) { // 捕获失败的 assert() }
并不是revert() 和 require()可以用Error(string memory reason)来捕获,而是revert("reasonString"), require(false, "reasonString")才可以。
从根本上来说,是revert的错误是Error(string)类型的时候才可以。
举几个反例,revert(), revert自定义error,require(false), 这些都不会是Error(string),因此不会被这个分支捕获。
例如下面的代码,运行execute之后会是2个CatchByte事件,而不是CatchEvent。
`
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
contract Test { // 成功event event SuccessEvent();
function revertWithoutString() external pure returns(bool success){
revert();
return true;
}
function requireWithoutString() external pure returns(bool success){
require(false);
return true;
}
// 失败event
event CatchEvent(string message);
event CatchByte(bytes data);
function execute() external returns (bool success) {
try Test(this).revertWithoutString() returns(bool _success){
return _success;
} catch Error(string memory reason){
emit CatchEvent(reason);
} catch (bytes memory reason) {
emit CatchByte(reason);
}
try Test(this).requireWithoutString() returns(bool _success){
return _success;
} catch Error(string memory reason){
emit CatchEvent(reason);
} catch (bytes memory reason) {
emit CatchByte(reason);
}
}
} `
感谢,很细节,学到了。你提个pr更新下这里?
👍🏻