Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
pseudobun opened this issue Jan 26, 2024 · 0 comments
Open

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

pseudobun opened this issue Jan 26, 2024 · 0 comments
Labels
proposal General proposal regarding Masca

Comments

@pseudobun
Copy link
Member

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,
    };
  }
}
@pseudobun pseudobun added the proposal General proposal regarding Masca label Jan 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
proposal General proposal regarding Masca
Projects
None yet
Development

No branches or pull requests

1 participant