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.
catch
safe: true
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> Copy
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> Copy
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> Copy
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> Copy
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>
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 thesafe: true
option to assume the function cannot throw.Type Param: T
The function type to execute (sync or async).
Type Param: E
The error type to return if
catch
is used.Example: Sync Try-Catch
Example: Sync Safe
Example: Async Try-Catch
Example: Async Safe