blockchain-lab-um / masca

Snap for managing VCs and DIDs in MetaMask
https://masca.io
Apache License 2.0
51 stars 16 forks source link

[proposal]: define and throw our own optional error codes #556

Open pseudobun opened 7 months ago

pseudobun commented 7 months ago

Motivation

An example of where this could be useful has been implemented in #554 see line 106. This is a temporary workaround which should also be addressed and fixed when implementing this proposal. This case (and many others) could be handled more easily if the error had an error code:

switch (error.code) {
    case 4000:
        // do something for this error handling
        break;
    default:
        // do something for general handling
        break;
}

Proposal

Updating ResultObject type to something like this:

export type Result<T> = {
  success: boolean;
} & (
  | {
      success: true;
      data: T;
    }
  | {
      success: false;
      error: string;
      code?: number; // Optional code parameter added here
    }
);

export const isError = <T>(
  result: Result<T>
): result is { success: false; error: string; code?: number } =>
  !result.success;

export const isSuccess = <T>(
  result: Result<T>
): result is { success: true; data: T } => result.success;

export class ResultObject {
  static success<T>(data: T): Result<T> {
    return { success: true, data };
  }

  static error<T>(error: string, code?: number): Result<T> {
    return {
      success: false,
      error,
      code,
    };
  }
}