Solidity 0.6.x options: strive/catch assertion

The try/catch syntax introduced in 0.6.0 is arguably the biggest leap in error handling capabilities in Solidity, since reason strings for revert other require were released in v0.4.22. both try other catch have been reserved keywords since v0.5.9 and now we can use them to handle failures in external function calls without rolling back the complete transaction (state changes in the called function are still rolled back, but the ones in the calling function are not).

We are moving one step away from the purist “all-or-nothing” approach in a transaction lifecycle, which falls short of practical behavior we often want.

Handling external call failures

The try/catch statement allows you to react on failed external calls and contract creation calls, so you cannot use it for internal function calls. Note that to wrap a public function call within the same contract with try/catch, it can be made external by calling the function with this..

The example below demonstrates how try/catch is used in a factory pattern where contract creation might fail. The following CharitySplitter contract requires a mandatory address property _owner in its constructor.

pragma solidity ^0.6.1;

contract CharitySplitter {
address public owner;
constructor (address _owner) public {
require(_owner != address(0), “no owner provided”);
owner = _owner;
}
}

There is a factory contract — CharitySplitterFactory which is used to create and manage instances of CharitySplitter. In the factory we can wrap the new CharitySplitter(charityOwner) in a try/catch as a failsafe for when that constructor might fail because of an empty charityOwner being passed.

pragma solidity ^0.6.1;
import “./CharitySplitter.sol”;
contract CharitySplitterFactory {
mapping (address => CharitySplitter) public charitySplitters;
uint public errorCount;
event ErrorHandled(string reason);
event ErrorNotHandled(bytes reason);
functions createCharitySplitter(address charityOwner) public {
try new CharitySplitter(charityOwner)
returns (CharitySplitter newCharitySplitter)
{
charitySplitters[msg.sender] = newCharitySplitter;
} catch {
errorCount++;
}
}
}

Note that with try/catch, only exceptions happening inside the external call itself are caught. Errors inside the expression are not caught, for example if the input parameter for the new CharitySplitter is itself part of an internal call, any errors it raises will not be caught. Sample demonstrating this behavior is the modified createCharitySplitter functions. Here the CharitySplitter constructor input parameter is retrieved dynamically from another function — getCharityOwner. If that function reverts, in this example with “revert-required-for-testing”that will not be caught in the try/catch statement.

functions createCharitySplitter(address _charityOwner) public {
try new CharitySplitter(getCharityOwner(_charityOwner, false))
returns (CharitySplitter newCharitySplitter)
{
charitySplitters[msg.sender] = newCharitySplitter;
} catch (bytes memory reason) {
...
}
}
functions getCharityOwner(address _charityOwner, bool _toPass)
internal returns (address) {
require(_toPass, “revert-required-for-testing”);
return _charityOwner;
}

Retrieving the error message

We can further extend the try/catch logic in the createCharitySplitter function to retrieve the error message if one was emitted by a failing revert or require and emit it in an event. There are two ways to achieve this:

1. Using catch Error(string memory reason)

functions createCharitySplitter(address _charityOwner) public {
try new CharitySplitter(_charityOwner) returns (CharitySplitter newCharitySplitter)
{
charitySplitters[msg.sender] = newCharitySplitter;
}
catchError(string memory reason)
{
errorCount++;
CharitySplitter newCharitySplitter = new
CharitySplitter(msg.sender);
charitySplitters[msg.sender] = newCharitySplitter;
// emitting the error in event
emit ErrorHandled(reason);
}
catch
{
errorCount++;
}
}

Which emits the following event on a failed constructor require error:

CharitySplitterFactory.ErrorHandled(
reason: ‘no-owner-provided’ (type: string)
)

2. Using catch (bytes memory reason)

functions createCharitySplitter(address charityOwner) public {
try new CharitySplitter(charityOwner)
returns (CharitySplitter newCharitySplitter)
{
charitySplitters[msg.sender] = newCharitySplitter;
}
catch (bytes memory reason) {
errorCount++;
emit ErrorNotHandled(reason);
}
}

Which emits the following event on a failed constructor require error:

CharitySplitterFactory.ErrorNotHandled(
reason: hex’08C379A00000000000000000000000000000000000000000000000000000000000000000000000000F2D6E65726F765640000000000000000000000000000 (type: bytes)

The above two methods for retrieving the error string produce a similar result. The advantage of the second method is that it is also executed if ABI decoding the error string fails or if no reason was provided.

Future plans

There are plans to release support for error types meaning we will be able to declare errors in a similar way to events allowing us to catch different type of errors, for example:

catch CustomErrorA(uint data1) {}
catch CustomErrorB(uint[] memory data2) {}
catch {}


Share post on

Sonic BTC is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Ethereum

ÐΞVcon-0 Recap

Day 1 - Monday 24th Nov - ÐΞV: Mission and Processes The first day...

By Roger Gofman
Gav’s Ethereum ÐΞV Replace IV Ethereum

Gav’s Ethereum ÐΞV Replace IV

Time for another update! A lot has happened since ÐΞVcon-0, our internal developer conference....

By Roger Gofman
Secret Sharing DAOs: The Different Crypto 2.0 Ethereum

Secret Sharing DAOs: The Different Crypto 2.0

The crypto 2.0 industry has been making strong progress in the past year developing...

By Roger Gofman
On Silos Ethereum

On Silos

One of the criticisms that many people have made about the current direction of...

By Roger Gofman
Ethereum Group Survey Ethereum

Ethereum Group Survey

Back in November, we created a short survey for the Ethereum community to help...

By Roger Gofman
Mild Shoppers and Proof of Stake Ethereum

Mild Shoppers and Proof of Stake

Special thanks to Vlad Zamfir and Jae Kwon for many of the ideas described...

By Roger Gofman
The P + epsilon assault Ethereum

The P + epsilon assault

Special thanks to Andrew Miller for the idea of ​​this attack and to Zack...

By Roger Gofman
Attending to the border Ethereum

Attending to the border

So first some background. We already shared a bit about what to expect from...

By Roger Gofman

Latest Posts

Dot sample [DOT] could possibly be on a brief bullish dash thanks to those developments – AMBCrypto Information Polkadot

Dot sample [DOT] could possibly be on a brief bullish dash thanks to those developments – AMBCrypto Information

Dot pattern [DOT] and Cardano [ADA] Blockchains are known for their intense developer activity...

By Roger Gofman
Stellar

Prime DeFi Funding Rounds in LatAm – 2022 – LatamList

Interest in crypto and DeFi has exploded in Latin America over the past year....

By Roger Gofman
CryptoSlate Wrapped Day by day: Binance Targets Cyber ​​Monetary Crimes;  CEL tanks after Alex Mashinsky resigns from Celsius – CryptoSlate Binance

CryptoSlate Wrapped Day by day: Binance Targets Cyber ​​Monetary Crimes; CEL tanks after Alex Mashinsky resigns from Celsius – CryptoSlate

Some of the biggest news in the cryptosphere for September 27 include Binance's new...

By Roger Gofman
Ethereum

ÐΞVcon-0 Recap

Day 1 - Monday 24th Nov - ÐΞV: Mission and Processes The first day...

By Roger Gofman
ITS HAPPENING AGAIN (Historical past Repeating)!! Ethereum Worth Prediction, Bitcoin Information In the present day (BTC & ETH) Videos

ITS HAPPENING AGAIN (Historical past Repeating)!! Ethereum Worth Prediction, Bitcoin Information In the present day (BTC & ETH)

ITS HAPPENING AGAIN (History Repeating)!! Ethereum Price Prediction, Bitcoin News Today (BTC & ETH)...

By Roger Gofman
Rocketize Token, Child DogeCoin and Shiba Predator: These meme cash will show you how to keep away from the unfavorable results of the bear market – NewsWatch Dogecoin

Rocketize Token, Child DogeCoin and Shiba Predator: These meme cash will show you how to keep away from the unfavorable results of the bear market – NewsWatch

It is possible to see an upward trend in transaction volume with the new...

By Roger Gofman
Cardano (ADA) is listed by the Swiss Crypto Asset Administration Service – U.At this time Cardano

Cardano (ADA) is listed by the Swiss Crypto Asset Administration Service – U.At this time

Alex Dovbnya A Swiss crypto wealth management app has added support for the Cardano...

By Roger Gofman
Astar Community’s Web3 Advert Showcases 329 Prime Manufacturers in Japan – FinanceFeeds Polkadot

Astar Community’s Web3 Advert Showcases 329 Prime Manufacturers in Japan – FinanceFeeds

Blockchain innovation hub Astar Network is making strides in driving Web3 adoption around the...

By Roger Gofman