Telegram-Mini-Apps / telegram-apps

Made from scratch TypeScript packages, examples and documentation you will surely need to start developing on Telegram Mini Apps.
https://docs.telegram-mini-apps.com/
MIT License
691 stars 191 forks source link

[Feature]: safe util function #508

Open defany opened 1 month ago

defany commented 1 month ago

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