Wagmi how to catch and display MetaMask errors?

860 views Asked by At

I am using wagmi to connect to MetaMask wallet to get some information and I noticed that I can get 2 errors.

One error is ConnectorNotFoundError: Connector not found at MetaMaskConnector.connect... if I don't have the MetaMask extension installed. The other error is {code: -32002, message: 'Already processing eth_requestAccounts. Please wait.'} is the connecting process that is started is not finished.

How can I check for those errors and display their message or a custom one?

I used connect from wagmi hook useConnect and I tried to use a try-catch block but it did not catch the errors. Also, the useConnect hook comes with error but if I console log the error it comes as null, even if I get any of the 2 errors.

  const { connect, error } = useConnect({
    connector: MetaMask,
  });

  const handleClick = () => {
    console.log(error)
    try {
      connect();
    } catch (err: any) {
      console.error('Error connecting:', err);
    }
  };
1

There are 1 answers

0
Morton On

try catch is not working in the case, you should try put call back function onError into the useConnect hook.

const { connect, connectors, error, isLoading, pendingConnector } = useConnect({
        onSuccess(data, variables, context) {
            const { account, chain } = data;
        },
        onError(error, variables, context) {
            console.log('error', { error, variables, context });
            if (variables.connector.id === 'metaMask') {
                setErrorMsg('An unexpected error occurred.');
            }
        },
    });