Ethereum.on How to get error if chain is not added into metamask yet

With this method app is listening for chain change:

    ethereum.on('chainChanged', (chainId) => {
})

but if the chain to which the user is going is not added yet into metamask it throws :

inpage.js:1 MetaMask - RPC Error: Unrecognized chain ID "0x89".
Try adding the chain using wallet_addEthereumChain first. Object

of course, there is a method to add a new chain into metamask but how to catch this metamask error? try and catch outside ethereum.on gives nothing

Thanks!


write a mapping for metamask networks:

const NETWORKS = {
  1: "Ethereum Main Network",
  3: "Ropsten Test Network",
  4: "Rinkeby Test Network",
  5: "Goerli Test Network",
  42: "Kovan Test Network",
  56: "Binance Smart Chain",
  1337: "Ganache",
};

set your target networK

const targetNetwork = NETWORKS[process.env.TARGET_CHAIN_ID];

const getChainId= async () => {
      const chainId = await web3.eth.getChainId();
      if (!chainId) {
        throw new Error(
          "Cannot retrieve an account. Please refresh the browser"
        );
      }
      return NETWORKS[chainId];
    }
  );