happy-rusty
    Preparing search index...

    Function tryResult

    • Executes a function and captures any thrown exception as an Err. If the function executes successfully, returns Ok with the result.

      Use this to convert traditional try-catch error handling to Result-based handling.

      Similar to Promise.try, this function accepts optional arguments that are passed to the function.

      Type Parameters

      • T

        The type of the value returned by the function.

      • E = Error

        The type of the error that may be thrown, defaults to Error.

      • Args extends unknown[] = []

        The types of the arguments to pass to the function.

      Parameters

      • fn: (...args: Args) => T

        A function that may throw an exception.

      • ...args: Args

        Arguments to pass to the function.

      Returns Result<T, E>

      Ok<T> if the function succeeds, or Err<E> if it throws.

      1.7.0

      // Parse JSON safely with arguments
      const result = tryResult(JSON.parse, jsonString);
      result.inspect(data => console.log('Parsed:', data))
      .inspectErr(err => console.error('Invalid JSON:', err));
      // Validate URL - using closure form
      const result = tryResult(() => new URL(input));
      if (result.isOk()) {
      console.log('Valid URL:', result.unwrap().href);
      }
      // With custom error type
      const result = tryResult<Config, ConfigError, [string]>(parseConfig, raw);