rpc-errors icon indicating copy to clipboard operation
rpc-errors copied to clipboard

Property 'cause' does not exist on type 'Json & ExactOptionalGuard'

Open Taewa opened this issue 2 years ago • 3 comments

Hi, My main purpose of using serializeError is to get cause. it works perfectly but I get a following error

Property 'cause' does not exist on type 'Json & ExactOptionalGuard'.

What would be the appropriate type of it? My code is below:

const err = serializeError(e);  // 'e' from smart contract error
const cause = err?.data?.cause?.reason; // Property 'cause' does not exist on type 'Json & ExactOptionalGuard'

Taewa avatar Jan 04 '24 17:01 Taewa

Hi @Taewa, it's possible for data to not contain a cause property, so you have to check for the existence of this property first before attempting to access it.

mcmire avatar Jan 08 '24 19:01 mcmire

@Taewa this is what I did and seems to work:

  .catch((e: any) => {
        const serializedError = serializeError(e) as SerializedError;
        const errorData = serializedError.data as MetaMaskErrorData; // Type assertion here
        if (errorData?.cause) {
          console.log("Serialized RPC Error:", errorData.cause.reason);
        }
        console.log(e.code);
      });
  create these interfaces:
   interface MetaMaskErrorData {
  cause?: {
    [key: string]: any; // Using an index signature for flexibility
  };
  [key: string]: any; // Allow for other dynamic properties
}

interface SerializedError {
  code: number;
  message: string;
  data?: MetaMaskErrorData;
}

Hope this helps :)

0xelisa avatar Jan 25 '24 16:01 0xelisa