Reputation: 129
In javascript I run contract's method
contract[methodName](...params, { from: myAccount }, (err, response) => {
console.log('get transaction', methodName, err, response);
if (err) return reject(err);
resolve(response);
});
and then reject transaction through MetaMask. In console get an error
MetaMask - RPC Error: Error: MetaMask Tx Signature: User denied transaction signature.
But I can't catch this error in my code. Callback not working.
How can i catch this error in JS?
Upvotes: 12
Views: 14239
Reputation: 364
I was also facing the same issue and I fixed it by using this library
https://github.com/enzoferey/ethers-error-parser
npm install @enzoferey/ethers-error-parser
import { getParsedEthersError } from "@enzoferey/ethers-error-parser";
try {
const transaction = await someContract.someMethod();
await transaction.wait();
} catch (error) {
const parsedEthersError = getParsedEthersError(error);
// parsedError.errorCode - contains a well defined error code (see full list below)
// parsedError.context - contains a context based string providing additional information
// profit !
}
If the user rejects the transaction then the error code will be REJECTED_TRANSACTION
You can find a complete list of error codes from official docs here: https://github.com/MetaMask/eth-rpc-errors/blob/main/src/error-constants.ts
Upvotes: 0
Reputation: 1254
Do this if you are using Ethers library:
contract.methodName(...params, { from: myAccount })
.then(tx => {
//do whatever you want with tx
})
.catch(e => {
if (e.code === 4001){
//user rejected the transaction
}
});
Upvotes: 2