@praha/byethrow
    Preparing search index...

    Function try

    Wraps a function execution (sync or async) in a Result or ResultAsync type, capturing errors and returning them in a structured way.

    You can use either a custom catch handler or rely on the safe: true option to assume the function cannot throw.

    The function type to execute (sync or async).

    The error type to return if catch is used.

    import { Result } from '@praha/byethrow';

    const fn = Result.try({
    try: (x: number) => {
    if (x < 0) throw new Error('Negative!');
    return x * 2;
    },
    catch: (error) => new Error('Oops!', { cause: error }),
    });

    const result = fn(5); // Result.Result<number, Error>
    import { Result } from '@praha/byethrow';

    const fn = Result.try({
    safe: true,
    try: (x: number) => x + 1,
    });

    const result = fn(1); // Result.Result<number, never>
    import { Result } from '@praha/byethrow';

    const fn = Result.try({
    try: async (id: string) => await fetch(`/api/data/${id}`),
    catch: (error) => new Error('Oops!', { cause: error }),
    });

    const result = await fn('abc'); // Result.ResultAsync<Response, Error>
    import { Result } from '@praha/byethrow';

    const fn = Result.try({
    safe: true,
    try: async () => await Promise.resolve('ok'),
    });

    const result = await fn(); // Result.ResultAsync<string, never>
    • Type Parameters

      • T extends (...args: readonly any[]) => Promise<any>
      • E

      Parameters

      • options: { catch: (error: unknown) => E; try: T }

      Returns (...args: Parameters<T>) => ResultAsync<Awaited<ReturnType<T>>, E>

    • Type Parameters

      • T extends (...args: readonly any[]) => Promise<any>

      Parameters

      • options: { safe: true; try: T }

      Returns (...args: Parameters<T>) => ResultAsync<Awaited<ReturnType<T>>, never>

    • Type Parameters

      • T extends (...args: readonly any[]) => any
      • E

      Parameters

      • options: { catch: (error: unknown) => E; try: T }

      Returns (...args: Parameters<T>) => Result.Result<ReturnType<T>, E>

    • Type Parameters

      • T extends (...args: readonly any[]) => any

      Parameters

      • options: { safe: true; try: T }

      Returns (...args: Parameters<T>) => Result.Result<ReturnType<T>, never>