0

After using a function in solidity with ether js, if that function fails, how can I detect this error with ether js?

error error_name();
contract example(){

  function f(){
    revert error_name();
  }
}

2 Answers 2

0

Here's how you can detect your error with ethers.js quite easily using ethers-decode-error.

Install ethers-decode-error in your project:

npm install ethers-decode-error --save

Next, the following code will help you get the name of the custom error in your solidity contract:

import { ErrorDecoder, DecodedError } from 'ethers-decode-error'

// This is the instance of your example smart contract
const exampleContract = new ethers.Contract('0x1234', abi, provider)

const errorDecoder = ErrorDecoder.create([exampleContract.interface])

try {
  const tx = await exampleContract.f()
  await tx.wait()
} catch (err) {
  const decodedError = await errorDecoder.decode(err)

  // Prints "error_name" which is what you have named the error in your contract
  console.log('Custom error name:', decodedError.name)

  const reason = customReasonMapper(decodedError)
  // Prints "This is a custom message for error_name from example contract."
  console.log('Custom error message:', reason)
}

const customReasonMapper = ({ name, reason }: DecodedError): string => {
  switch (name) {
    case 'error_name':
      return 'This is a custom message for error_name from example contract.'

    // You can match other custom errors you may have in your contract here...
    // case 'MyOtherError': ...

    // Captures other error messages
    default:
      return reason ?? 'There was an error'
  }
}

You can find more examples for handling solidity custom errors here. :)

-1

On frontend:


const [error, setError] = useState();

const call = () => {
 try{
 //ethers logics
}catch(err){
 setError(err)
}
}

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.