logo
byethrow
Guide
Examples
API Reference
Guide
Examples
API Reference
logo
byethrow

Getting Started

Introduction
Why byethrow?
Quick Start
Importing Result

Best Practices

Result vs throw
Custom Error
Pattern Matching

Tools & Integrations

MCP Server
ESLint Plugin

Last Updated: 2025/10/13 08:39:30

Previous PageWhy byethrow?
Next PageImporting Result

#Quick Start

Get up and running with @praha/byethrow in minutes!

This guide will walk you through the essential concepts and usage patterns.

#Installation

Install the package using your preferred package manager:

npm
yarn
pnpm
bun
npm install @praha/byethrow

#Basic Concepts

@praha/byethrow provides a Result type that represents the outcome of an operation that might fail. Instead of throwing exceptions, functions return a Result that can be either:

  • Success: Contains a value of type T
  • Failure: Contains an error of type E

This approach makes error handling explicit and predictable.

#Your First Result

Let's start with a simple example:

import { 
import Result
Result
} from '@praha/byethrow';
// Creating a successful result const
const success: Result.Result<string, never>
success
=
import Result
Result
.
const succeed: <string>(value: string) => Result.Result<string, never> (+1 overload)
succeed
('Hello, World!');
// Creating a failed result const
const failure: Result.Result<never, Error>
failure
=
import Result
Result
.
const fail: <Error>(error: Error) => Result.Result<never, Error> (+1 overload)
fail
(new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
('Something went wrong'));
// Checking the result if (
import Result
Result
.
const isSuccess: <string>(result: Result.Result<string, unknown>) => result is Result.Success<string>

Type guard to check if a Result is a Success .

@function@typeParamT - The type of the success value.@paramresult - The Result to check.@returnstrue if the result is a Success, otherwise false.@example
import { Result } from '@praha/byethrow';

const result: Result.Result<number, string> = { type: 'Success', value: 10 };
if (Result.isSuccess(result)) {
  console.log(result.value); // Safe access to value
}
@categoryType Guards
isSuccess
(
const success: Result.Result<string, never>
success
)) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.
Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0 .1.100
log
(
const success: Result.Success<string>
success
.
value: string
value
); // "Hello, World!"
} if (
import Result
Result
.
const isFailure: <Error>(result: Result.Result<unknown, Error>) => result is Result.Failure<Error>

Type guard to check if a Result is a Failure .

@function@typeParamE - The type of the error value.@paramresult - The Result to check.@returnstrue if the result is a Failure, otherwise false.@example
import { Result } from '@praha/byethrow';

const result: Result.Result<number, string> = { type: 'Failure', error: 'Something went wrong' };
if (Result.isFailure(result)) {
  console.error(result.error); // Safe access to error
}
@categoryType Guards
isFailure
(
const failure: Result.Result<never, Error>
failure
)) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.
Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0 .1.100
log
(
const failure: Result.Failure<Error>
failure
.
error: Error
error
.
Error.message: string
message
); // "Something went wrong"
}

#Handling Operations That Might Fail

Use Result.try to wrap functions that might throw exceptions:

import { 
import Result
Result
} from '@praha/byethrow';
const
const parseNumber: (input: string) => Result.Result<number, Error>
parseNumber
=
import Result
Result
.
try<(input: string) => number, Error>(options: {
    try: (input: string) => number;
    catch: (error: unknown) => Error;
}): (input: string) => Result.Result<number, Error> (+7 overloads)
export try

Wraps a function execution (sync or async) or a Promise 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.

@function@typeParamT - The function type to execute (sync or async) or a Promise type.@typeParamE - The error type to return if catch is used.@example

Sync try-catch

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>
@example

Sync try-catch with immediate execution

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

const result = Result.try({
immediate: true,
try: () => {
const x = Math.random() * 10 - 5;
if (x < 0) throw new Error('Negative!');
return x * 2;
},
catch: (error) => new Error('Oops!', { cause: error }),
});

// result is Result<number, Error>
@example

Sync safe

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

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

const result = fn(1); // Result.Result<number, never>
@example

Sync safe with immediate execution

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

const result = Result.try({
safe: true,
immediate: true,
try: () => Math.random() + 1,
});

// result is Result<number, never>
@example

Async try-catch

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>
@example

Async try-catch with immediate execution

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

const result = Result.try({
immediate: true,
try: () => fetch('/api/data'),
catch: (error) => new Error('Fetch failed', { cause: error }),
});

// result is ResultAsync<Response, Error>
@example

Async safe

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>
@example

Async safe with immediate execution

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

const result = Result.try({
safe: true,
immediate: true,
try: () => Promise.resolve('ok'),
});

// result is ResultAsync<string, never>
@categoryCreators
try
({
try: (input: string) => number
try
: (
input: string
input
: string) => {
const
const num: number
num
=
var Number: NumberConstructor
(value?: any) => number

An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers.

Number
(
input: string
input
);
if (
var Number: NumberConstructor

An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers.

Number
.
NumberConstructor.isNaN(number: unknown): boolean

Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter to a number. Only values of the type number, that are also NaN, result in true.

@paramnumber A numeric value.
isNaN
(
const num: number
num
)) {
throw new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
('Not a valid number');
} return
const num: number
num
;
},
catch: (error: unknown) => Error
catch
: (
error: unknown
error
) => new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
('Failed to parse number', {
ErrorOptions.cause?: unknown
cause
:
error: unknown
error
}),
}); const
const result: Result.Result<number, Error>
result
=
const parseNumber: (input: string) => Result.Result<number, Error>
parseNumber
('42');
if (
import Result
Result
.
const isSuccess: <number>(result: Result.Result<number, unknown>) => result is Result.Success<number>

Type guard to check if a Result is a Success .

@function@typeParamT - The type of the success value.@paramresult - The Result to check.@returnstrue if the result is a Success, otherwise false.@example
import { Result } from '@praha/byethrow';

const result: Result.Result<number, string> = { type: 'Success', value: 10 };
if (Result.isSuccess(result)) {
  console.log(result.value); // Safe access to value
}
@categoryType Guards
isSuccess
(
const result: Result.Result<number, Error>
result
)) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.
Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0 .1.100
log
(
const result: Result.Success<number>
result
.
value: number
value
); // 42
}

#Transforming Values

Use Result.map to transform successful values:

import { 
import Result
Result
} from '@praha/byethrow';
const
const double: (x: number) => number
double
= (
x: number
x
: number) =>
x: number
x
* 2;
const
const result: Result.Result<number, never>
result
=
import Result
Result
.
const pipe: <Result.Result<number, never>, Result.Result<number, never>>(a: Result.Result<number, never>, ab: (a: Result.Result<number, never>) => Result.Result<number, never>) => Result.Result<number, never> (+25 overloads)
pipe
(
import Result
Result
.
const succeed: <number>(value: number) => Result.Result<number, never> (+1 overload)
succeed
(21),
import Result
Result
.
const map: <Result.Result<number, never>, number>(fn: (a: number) => number) => (result: Result.Result<number, never>) => Result.Result<number, never> (+1 overload)
map
(
const double: (x: number) => number
double
)
); if (
import Result
Result
.
const isSuccess: <number>(result: Result.Result<number, unknown>) => result is Result.Success<number>

Type guard to check if a Result is a Success .

@function@typeParamT - The type of the success value.@paramresult - The Result to check.@returnstrue if the result is a Success, otherwise false.@example
import { Result } from '@praha/byethrow';

const result: Result.Result<number, string> = { type: 'Success', value: 10 };
if (Result.isSuccess(result)) {
  console.log(result.value); // Safe access to value
}
@categoryType Guards
isSuccess
(
const result: Result.Result<number, never>
result
)) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.
Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0 .1.100
log
(
const result: Result.Success<number>
result
.
value: number
value
); // 42
}

#Chaining Operations

One of the most powerful features is chaining operations together using Result.pipe:

import { 
import Result
Result
} from '@praha/byethrow';
const
const validateId: (id: string) => Result.Failure<Error> | Result.Success<string>
validateId
= (
id: string
id
: string) => {
if (!
id: string
id
.
String.startsWith(searchString: string, position?: number): boolean

Returns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at position. Otherwise returns false.

startsWith
('u')) {
return
import Result
Result
.
const fail: <Error>(error: Error) => Result.Result<never, Error> (+1 overload)
fail
(new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
('Invalid ID format'));
} return
import Result
Result
.
const succeed: <string>(value: string) => Result.Result<string, never> (+1 overload)
succeed
(
id: string
id
);
}; const
const findUser: (id: string) => Result.Failure<Error> | Result.Success<{
    id: string;
    name: string;
}>
findUser
= (
id: string
id
: string) => {
// Simulate a database lookup if (
id: string
id
=== 'u123') {
return
import Result
Result
.
const succeed: <{
    id: string;
    name: string;
}>(value: {
    id: string;
    name: string;
}) => Result.Result<{
    id: string;
    name: string;
}, never> (+1 overload)
succeed
({
id: string
id
,
name: string
name
: 'John Doe' });
} return
import Result
Result
.
const fail: <Error>(error: Error) => Result.Result<never, Error> (+1 overload)
fail
(new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
('User not found'));
}; const
const toWelcome: (user: Result.InferSuccess<typeof findUser>) => string
toWelcome
= (
user: {
    id: string;
    name: string;
}
user
:
import Result
Result
.
type InferSuccess<T> = [T] extends [(...args: any[]) => Result.ResultMaybeAsync<infer U, any>] ? U : [T] extends [Result.ResultMaybeAsync<infer U, any>] ? U : never

Infers the Success value type T from a Result or a function returning a Result.

@typeParamT - A ResultMaybeAsync type or a function returning it.@example

From a result object

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

type R = Result.Result<number, string>;
type SuccessValue = Result.InferSuccess<R>; // number
@example

From a function

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

const fn = () => Promise.resolve({ type: 'Success', value: 123 } as const);
type SuccessValue = Result.InferSuccess<typeof fn>; // number
@categoryInfer Types
InferSuccess
<typeof
const findUser: (id: string) => Result.Failure<Error> | Result.Success<{
    id: string;
    name: string;
}>
findUser
>) => {
return `Welcome, ${
user: {
    id: string;
    name: string;
}
user
.
name: string
name
}!`;
}; // Chain multiple operations const
const result: Result.Result<string, Error>
result
=
import Result
Result
.
const pipe: <Result.Result<string, never>, Result.Result<string, Error>, Result.Result<{
    id: string;
    name: string;
}, Error>, Result.Result<string, Error>>(a: Result.Result<string, never>, ab: (a: Result.Result<string, never>) => Result.Result<string, Error>, bc: (b: Result.Result<string, Error>) => Result.Result<{
    id: string;
    name: string;
}, Error>, cd: (c: Result.Result<{
    id: string;
    name: string;
}, Error>) => Result.Result<string, Error>) => Result.Result<...> (+25 overloads)
pipe
(
import Result
Result
.
const succeed: <string>(value: string) => Result.Result<string, never> (+1 overload)
succeed
('u123'),
import Result
Result
.
const andThen: <Result.Result<string, never>, Result.Failure<Error> | Result.Success<string>>(fn: (a: string) => Result.Failure<Error> | Result.Success<string>) => (result: Result.Result<string, never>) => Result.Result<string, Error> (+1 overload)
andThen
(
const validateId: (id: string) => Result.Failure<Error> | Result.Success<string>
validateId
),
import Result
Result
.
const andThen: <Result.Result<string, Error>, Result.Failure<Error> | Result.Success<{
    id: string;
    name: string;
}>>(fn: (a: string) => Result.Failure<Error> | Result.Success<{
    id: string;
    name: string;
}>) => (result: Result.Result<string, Error>) => Result.Result<{
    id: string;
    name: string;
}, Error> (+1 overload)
andThen
(
const findUser: (id: string) => Result.Failure<Error> | Result.Success<{
    id: string;
    name: string;
}>
findUser
),
import Result
Result
.
const map: <Result.Result<{
    id: string;
    name: string;
}, Error>, string>(fn: (a: {
    id: string;
    name: string;
}) => string) => (result: Result.Result<{
    id: string;
    name: string;
}, Error>) => Result.Result<string, Error> (+1 overload)
map
(
const toWelcome: (user: Result.InferSuccess<typeof findUser>) => string
toWelcome
)
); if (
import Result
Result
.
const isSuccess: <string>(result: Result.Result<string, unknown>) => result is Result.Success<string>

Type guard to check if a Result is a Success .

@function@typeParamT - The type of the success value.@paramresult - The Result to check.@returnstrue if the result is a Success, otherwise false.@example
import { Result } from '@praha/byethrow';

const result: Result.Result<number, string> = { type: 'Success', value: 10 };
if (Result.isSuccess(result)) {
  console.log(result.value); // Safe access to value
}
@categoryType Guards
isSuccess
(
const result: Result.Result<string, Error>
result
)) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.
Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0 .1.100
log
(
const result: Result.Success<string>
result
.
value: string
value
); // "Welcome, John Doe!"
}

#Error Handling

Handle errors gracefully with Result.orElse:

import { 
import Result
Result
} from '@praha/byethrow';
const
const riskyOperation: () => Result.Result<never, Error>
riskyOperation
= () =>
import Result
Result
.
const fail: <Error>(error: Error) => Result.Result<never, Error> (+1 overload)
fail
(new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
('Operation failed'));
const
const fallback: () => Result.Result<string, never>
fallback
= () =>
import Result
Result
.
const succeed: <string>(value: string) => Result.Result<string, never> (+1 overload)
succeed
('Default value');
const
const result: Result.Result<string, never>
result
=
import Result
Result
.
const pipe: <Result.Result<never, Error>, Result.Result<string, never>>(a: Result.Result<never, Error>, ab: (a: Result.Result<never, Error>) => Result.Result<string, never>) => Result.Result<string, never> (+25 overloads)
pipe
(
const riskyOperation: () => Result.Result<never, Error>
riskyOperation
(),
import Result
Result
.
const orElse: <Result.Result<never, Error>, Result.Result<string, never>>(fn: (a: Error) => Result.Result<string, never>) => (result: Result.Result<never, Error>) => Result.Result<string, never> (+1 overload)
orElse
(
const fallback: () => Result.Result<string, never>
fallback
)
); if (
import Result
Result
.
const isSuccess: <string>(result: Result.Result<string, unknown>) => result is Result.Success<string>

Type guard to check if a Result is a Success .

@function@typeParamT - The type of the success value.@paramresult - The Result to check.@returnstrue if the result is a Success, otherwise false.@example
import { Result } from '@praha/byethrow';

const result: Result.Result<number, string> = { type: 'Success', value: 10 };
if (Result.isSuccess(result)) {
  console.log(result.value); // Safe access to value
}
@categoryType Guards
isSuccess
(
const result: Result.Result<string, never>
result
)) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.
Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0 .1.100
log
(
const result: Result.Success<string>
result
.
value: string
value
); // "Default value"
}

#Working with Async Operations

@praha/byethrow works seamlessly with asynchronous operations:

import { 
import Result
Result
} from '@praha/byethrow';
const
const validateId: (id: string) => Result.Failure<Error> | Result.Success<string>
validateId
= (
id: string
id
: string) => {
if (!
id: string
id
.
String.startsWith(searchString: string, position?: number): boolean

Returns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at position. Otherwise returns false.

startsWith
('u')) {
return
import Result
Result
.
const fail: <Error>(error: Error) => Result.Result<never, Error> (+1 overload)
fail
(new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
('Invalid ID format'));
} return
import Result
Result
.
const succeed: <string>(value: string) => Result.Result<string, never> (+1 overload)
succeed
(
id: string
id
);
}; const
const findUser: (userId: string) => Result.ResultAsync<any, Error>
findUser
=
import Result
Result
.
try<(userId: string) => Promise<any>, Error>(options: {
    try: (userId: string) => Promise<any>;
    catch: (error: unknown) => Error;
}): (userId: string) => Result.ResultAsync<any, Error> (+7 overloads)
export try

Wraps a function execution (sync or async) or a Promise 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.

@function@typeParamT - The function type to execute (sync or async) or a Promise type.@typeParamE - The error type to return if catch is used.@example

Sync try-catch

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>
@example

Sync try-catch with immediate execution

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

const result = Result.try({
immediate: true,
try: () => {
const x = Math.random() * 10 - 5;
if (x < 0) throw new Error('Negative!');
return x * 2;
},
catch: (error) => new Error('Oops!', { cause: error }),
});

// result is Result<number, Error>
@example

Sync safe

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

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

const result = fn(1); // Result.Result<number, never>
@example

Sync safe with immediate execution

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

const result = Result.try({
safe: true,
immediate: true,
try: () => Math.random() + 1,
});

// result is Result<number, never>
@example

Async try-catch

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>
@example

Async try-catch with immediate execution

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

const result = Result.try({
immediate: true,
try: () => fetch('/api/data'),
catch: (error) => new Error('Fetch failed', { cause: error }),
});

// result is ResultAsync<Response, Error>
@example

Async safe

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>
@example

Async safe with immediate execution

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

const result = Result.try({
safe: true,
immediate: true,
try: () => Promise.resolve('ok'),
});

// result is ResultAsync<string, never>
@categoryCreators
try
({
try: (userId: string) => Promise<any>
try
: async (
userId: string
userId
: string) => {
const
const response: Response
response
= await
function fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> (+1 overload)

MDN Reference

fetch
(`/api/users/${
userId: string
userId
}`);
return await
const response: Response
response
.
Body.json(): Promise<any>

MDN Reference

json
();
},
catch: (error: unknown) => Error
catch
: (
error: unknown
error
) => new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
('Failed to find user', {
ErrorOptions.cause?: unknown
cause
:
error: unknown
error
}),
}); const
const result: Result.Result<any, Error>
result
= await
import Result
Result
.
const pipe: <Result.Result<string, never>, Result.Result<string, Error>, Result.ResultAsync<any, Error>>(a: Result.Result<string, never>, ab: (a: Result.Result<string, never>) => Result.Result<string, Error>, bc: (b: Result.Result<string, Error>) => Result.ResultAsync<any, Error>) => Result.ResultAsync<any, Error> (+25 overloads)
pipe
(
import Result
Result
.
const succeed: <string>(value: string) => Result.Result<string, never> (+1 overload)
succeed
('u123'),
import Result
Result
.
const andThen: <Result.Result<string, never>, Result.Failure<Error> | Result.Success<string>>(fn: (a: string) => Result.Failure<Error> | Result.Success<string>) => (result: Result.Result<string, never>) => Result.Result<string, Error> (+1 overload)
andThen
(
const validateId: (id: string) => Result.Failure<Error> | Result.Success<string>
validateId
),
import Result
Result
.
const andThen: <Result.Result<string, Error>, Result.ResultAsync<any, Error>>(fn: (a: string) => Result.ResultAsync<any, Error>) => (result: Result.Result<string, Error>) => Result.ResultAsync<any, Error> (+1 overload)
andThen
(
const findUser: (userId: string) => Result.ResultAsync<any, Error>
findUser
),
); if (
import Result
Result
.
const isSuccess: <any>(result: Result.Result<any, unknown>) => result is Result.Success<any>

Type guard to check if a Result is a Success .

@function@typeParamT - The type of the success value.@paramresult - The Result to check.@returnstrue if the result is a Success, otherwise false.@example
import { Result } from '@praha/byethrow';

const result: Result.Result<number, string> = { type: 'Success', value: 10 };
if (Result.isSuccess(result)) {
  console.log(result.value); // Safe access to value
}
@categoryType Guards
isSuccess
(
const result: Result.Result<any, Error>
result
)) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.
Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0 .1.100
log
('User data:',
const result: Result.Success<any>
result
.
value: any
value
);
}

Happy coding with @praha/byethrow! 🚀