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

[Feature]: safe util function #508

Open
defany opened this issue Oct 17, 2024 · 0 comments
Open

[Feature]: safe util function #508

defany opened this issue Oct 17, 2024 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@defany
Copy link

defany commented Oct 17, 2024

Is your feature request related to a problem? Please describe.

Some of sdk methods are throwing errors, while some developers do not want to catch them by .catch() method or try {} catch {} construction, they want to see an error as a result of function execution.

Describe the solution you'd like

type SuccessResponse<T> = {
  success: true;
  data: T;
};

type ErrorResponse = {
  success: false;
  err: unknown;
};

type SafeExecuteResponse<T> = SuccessResponse<T> | ErrorResponse;

async function safeExecute<T>(callback: () => T | Promise<T>): Promise<SafeExecuteResponse<T>> {
  try {
    const data = await callback()

    return {
      success: true,
      data: data,
    };
  } catch (err) {
    return {
      success: false,
      err: err,
    };
  }
}

const example = async () => {
  const someSafeResponse = await safeExecute(() => {
    return 1
  })
  if (someSafeResponse.success) {
    console.info(`Yeey! We did it! ${someSafeResponse.data}`)
  }

  if (!someSafeResponse.success) {
    console.error(`Damn, this is not what we expected... ${someSafeResponse.err}`)
  }
} 

example()

Describe alternatives you've considered

No response

Additional context

No response

@defany defany added the enhancement New feature or request label Oct 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants