DEV Community

Cover image for How to handle Solidity errors with React and Wagmi hooks
Murat Can Yüksel
Murat Can Yüksel

Posted on • Updated on

How to handle Solidity errors with React and Wagmi hooks

If you're building a frontend for a blockchain protocol, you'll need to handle errors coming from the smart contracts. In Solidity, we will now learn about require statements.

Solidity require are statements that are added in the functions to stop them if a certain condition is not met. Think of the following scenario: Users can only call a function if a certain statement is true. In this case, the _amount must be higher than zero.

function myFunc(uint256 _amount){

require(\_amount > 0, "Amount must be greater than 0");

Enter fullscreen mode Exit fullscreen mode

Now, in the frontend, let's write the corresponding function using wagmi hooks with react

First we need to import the useWriteContract hook from wagmi like so :

import { useWriteContract } from "wagmi";
Enter fullscreen mode Exit fullscreen mode

Then, initiate it in our component as follows:

const { writeContract, failureReason} = useWriteContract();
Enter fullscreen mode Exit fullscreen mode

You see we also destructure failureReason from useWriteContract hook. We will use this failureReason to see why the function reverted.

Now let's call the Solidity function

const callMyFunc = async () => {

    try {




        functionName: "myFunc",

        args: [0],


    } catch (error) {




Enter fullscreen mode Exit fullscreen mode

This is just basic function call. The thing is, since we're passing zero as an argument, the function call will fail/revert. If we logged the failureReason, we'd get something like this:

"ContractFunctionExecutionError: The contract function "myFunc" reverted with the following reason:
Amount must be greater than 0.
Contract Call:
address: 0xD...dc5b6
function: myFunc()
sender: 0x1A...667D"

Of course, in a real world scenario, we'd not just log the error message but maybe display it with a pop-up. Totally up to you.

Top comments (2)

leandro_nnz profile image
Leandro Nuñez

Please, consider editing your article for readability. Thanks.

muratcanyuksel profile image
Murat Can Yüksel

sure mate