@jenova-marie/ts-rust-result - v2.2.18
    Preparing search index...

    Function tryResult

    • Wraps an async function in a try-catch block and returns a Result.

      Type Parameters

      • T

        The return type of the async function

      • E = Error

        The type of the error (defaults to Error)

      Parameters

      • fn: () => Promise<T>

        The async function to execute

      • shouldThrow: boolean = false

        Whether to throw the error instead of returning a Result (defaults to false)

      Returns Promise<Result<T, E>>

      A Promise that resolves to a Result containing either the function's return value or an error

      If shouldThrow is true and the function throws an error

      const result = await tryResult(async () => {
      const response = await fetch('/api/data')
      return response.json()
      })

      if (result.ok) {
      console.log(result.value) // The JSON data
      } else {
      console.error(result.error) // Any error that occurred
      }