Unable to capture Metamask Errors

I am attempting to invoke a smart contract using ethers.contract and the signer from ethers.providers.web3Provider to leverage MetaMask. If the transaction fails, I want to capture the error and either retry or invoke a different function. However, my project fails to capture the error from MetaMask. When I reject the transaction in MetaMask, it works as expected. Below is a snippet of my code:

import { ethers } from "ethers";
import { SignedChannel } from "../api/contractTypes/channel";
import { Web3Provider } from "../client/Provider";

export async function register(
  params: SignedChannel,
  adj: ethers.Contract,
  provider: ethers.providers.WebSocketProvider | Web3Provider
) {
  const registerParams = [params.serialize(), []];
  console.log("Calling register");
  const gasPrice = await provider.getGasPrice();
  const tx = await adj.functions["register"](...registerParams, {
    from: params.params.participants[0],
    gasPrice: gasPrice.mul(2),
    gasLimit: 30000000,
  });
  console.log("Result:", tx);
  tx.wait().then(async (receipt: any) => {
    console.log("Transaction confirmed in block:", receipt.blockNumber);

    const updatedReceipt = await provider.getTransactionReceipt(tx.hash);
    console.log(updatedReceipt);
  });
  return tx.hash;
}
try {
  //register channel
 await register(signedState, adj!, this.provider);
 this.listenToChannelUpdate(adj!);
} catch (err) {
 console.log("Error while register:", err);
 process.status = "failedRegister";
 process.error = new Error(
  ("Error while register: Invalid Signed State: " + err) as string
 );
 this.state.emitUpdateProcess(process.id);
}

If the Transaction fails, i would expect to see the Error with the added string: "Error while register..." but instead i get:

Uncaught (in promise) Error: transaction failed [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (transactionHash="0x829228b6c66278019247c93885b703958c0d7187b4c3307fe1a4cd03c5c495e1", transaction={"hash":"0x829228b6c66278019247c93885b703958c0d7187b4c3307fe1a4cd03c5c495e1","type":2,"accessList":null,"blockHash":null,"blockNumber":null,"transactionIndex":null,"confirmations":0,"from":"0xA298Fc05bccff341f340a11FffA30567a00e651f","gasPrice":{"type":"BigNumber","hex":"0xee6b2800"},"maxPriorityFeePerGas":{"type":"B... 

Answer №1

Discovering the issue, I realized that attempting to handle an error thrown within a promise using a try/catch-block is not allowed. Once I updated the conclude function to throw errors outside of the promise, the problem was resolved.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to Utilizing the Dracula Graph Library in Angular

Recently, I stumbled upon a JavaScript library that seems to be an ideal fit for my project. The library can be found at: After installing the necessary libraries using npm - npm i raphael graphdracula - new folders were created in node_modules and th ...

Enhance the performance of your React/NextJS app by controlling the rendering of a component and focusing on updating

I'm facing an issue with my NextJS application that showcases a list of audio tracks using an <AudioTrackEntry> component. This component receives props like the Track Title and a Link to the audio file from an external data source. Within the ...

Asserting types for promises with more than one possible return value

Struggling with type assertions when dealing with multiple promise return types? Check out this simplified code snippet: interface SimpleResponseType { key1: string }; interface SimpleResponseType2 { property1: string property2: number }; inter ...

SonarQube seems to be overlooking TypeScript files with the .ts extension

I'm currently setting up SonarQube on Jenkins for an Angular 2 project, but I'm facing an issue where Sonar isn't recognizing the TypeScript files with the .ts extension. Here's the current configuration: sonar.projectKey=App Name- An ...

The cursor in the Monaco editor from @monaco-editor/react is not aligning with the correct position

One issue I am facing with my Monaco editor is that the cursor is always placed before the current character rather than after it. For example, when typing a word like "policy", the cursor should be placed after the last character "y" but instead, it&apos ...

Is it possible to utilize the $ symbol within the ngOnInit or constructor functions?

I recently encountered an issue while trying to use the dollar sign ($) in my constructor function, specifically within ngOnInit() and translate.instant. Here is a snippet of the code that caused the problem: declare var $: any; { var SelectedDevice = ...

Tips for implementing generics in an abstract class that extends a React Component

I am in the process of developing a unique abstract class that extends a React Component. My goal is to establish default Props while allowing the components that extend the abstract class to supply their own props. interface Props { ...

Troubleshooting Angular 2 with TypeScript: Issue with view not refreshing after variable is updated in response handler

I encountered a problem in my Angular 2 project using TypeScript that I could use some help with. I am making a request to an API and receiving a token successfully. In my response handler, I am checking for errors and displaying them to the user. Oddly en ...

Error in Redux with TypeScript: "Argument of type 'AsyncThunkAction<any, number, {}>' is not compatible with parameter of type 'AnyAction'"

So I've been working on this dispatch function: const dispatch = useAppDispatch() const handleFetch = (e: React.MouseEvent<HTMLAnchorElement>) => { const target = e.target as Element dispatch(fetchCity(parseInt(ta ...

Limit pasted content in an Angular contenteditable div

Is there a way to limit the input in a contenteditable div? I am developing my own WYSIWYG editor and want to prevent users from pasting content from external websites and copying styles. I want to achieve the same effect as if the content was pasted into ...

Utilizing Vue class-style components for creating a recursive component

I'm currently working with a class-style component using the vue-property-decorator plugin. I want to create a recursive component that can use itself within its own structure. Here's a snippet of my code: <template> <ul> <li& ...

Exporting modules in TypeScript using "module.exports"

While working on my Yeoman generator, I initially wrote it in JavaScript like this: "use strict"; var Generator = require("yeoman-generator"); var chalk = rquire("chalk"); module.exports = class extends Generator { initializing() { this.log( c ...

Conditions are in an angular type provider with AOT

I am facing an issue with my Angular project that is compiled using AOT. I am trying to dynamically register a ClassProvider based on certain configurations. The simplified code snippet I am currently using is below: const isMock = Math.random() > 0.5; ...

Updating the state in React is causing significant delays

In my React project, I am utilizing the pdf-lib (JS library) for some intensive tasks using async/await. My goal is to update a progress bar by modifying the state. However, when I use setState within a setTimeout, the state changes are not reflected unt ...

The attribute 'map' is not found on the data type 'Observable<[{}, {}]>'

Struggling to incorporate map, PublishReplay, and other rxjs functions into Angular6, I keep encountering a compilation error stating "Property 'map' does not exist on type 'Observable<[{}, {}]>'" every time. The same issue arises ...

Troubleshooting: Unable to filter reducers in Redux when using the remove

I'm attempting to eliminate an element from an array using the filter method in this manner: removeDisplate: (state, action: PayloadAction<string>) => { console.log(action.payload); state.map((item) => { console.log(item.name); } ...

Are there any methods within Angular 2 to perform Angular binding within a string?

When creating an HTML template with routing, such as shown below: <ul class="sb-sub-menu"> <li> <a [routerLink]="['clientadd']">Client Add</a> </li> </ul> It functions as expected. However, w ...

Utilizing the power of the Google Calendar API with a service account in a Node.js environment

I have a vision to create an application with a specific feature set: Whenever there is a change in the user's Google calendar (an event is added, deleted, or edited), I want to receive updates with full event details. To achieve this, I understand ...

Event triggered by clicking on certain coordinates

Just starting with @asymmetrik/ngx-leaflet and Angular, so this might be a beginner's issue... I'm working on an Angular.io (v5) project that incorporates the @asymmetrik/ngx-leaflet-tutorial-ngcli Currently, I'm trying to retrieve the coo ...

Error 405: Angular encounters a method not supported while attempting to delete the entity

I have developed an application that performs CRUD operations on a list of entities. However, when attempting to delete an entity, the dialog box does not appear as expected. To start, I have a HttpService serving as the foundation for the CRUD operations ...