Yieldable Errors
Yieldable Errors are special types of errors that can be yielded directly within a generator function using Effect.gen. These errors allow you to handle them intuitively, without needing to explicitly invoke Effect.fail. This simplifies how you manage custom errors in your code.
The Data.Error
constructor provides a way to define a base class for yieldable errors.
Example (Creating and Yielding a Custom Error)
1import { import Effect
Effect, import Data
Data } from "effect"2
3// Define a custom error class extending Data.Error4class class MyError
MyError extends import Data
Data.const Error: new <A extends Record<string, any> = {}>(args: Equals<A, {}> extends true ? void : { readonly [P in keyof A]: A[P]; }) => YieldableError & Readonly<A>
Provides a constructor for a Case Class.
Error<{ (property) message: string
message: string }> {}5
6export const const program: Effect.Effect<void, MyError, never>
program = import Effect
Effect.const gen: <YieldWrap<Effect.Effect<never, MyError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<never, MyError, never>>, void, never>) => Effect.Effect<...> (+1 overload)
gen(function* () {7 // Yield a custom error (equivalent to failing with MyError)8 yield* new constructor MyError<{
message: string;
}>(args: {
readonly message: string;
}): MyError
Provides a constructor for a Case Class.
MyError({ (property) message: string
message: "Oh no!" })9})10
11import Effect
Effect.const runPromiseExit: <void, MyError>(effect: Effect.Effect<void, MyError, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Exit<void, MyError>>
Executes an effect and returns a `Promise` that resolves with an `Exit` describing the result.
Use `runPromiseExit` when you need detailed information about the outcome of the effect, including success or failure,
and you want to work with Promises.
runPromiseExit(const program: Effect.Effect<void, MyError, never>
program).(method) Promise<Exit<void, MyError>>.then<void, never>(onfulfilled?: ((value: Exit<void, MyError>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
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`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
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:
```js
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
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
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)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
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()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log)12/*13Output:14{15 _id: 'Exit',16 _tag: 'Failure',17 cause: { _id: 'Cause', _tag: 'Fail', failure: { message: 'Oh no!' } }18}19*/
The Data.TaggedError
constructor lets you define custom yieldable errors with unique tags. Each error has a _tag
property, allowing you to easily distinguish between different error types. This makes it convenient to handle specific tagged errors using functions like Effect.catchTag or Effect.catchTags.
Example (Handling Multiple Tagged Errors)
1import { import Effect
Effect, import Data
Data, import Random
Random } from "effect"2
3// An error with _tag: "Foo"4class class FooError
FooError extends import Data
Data.const TaggedError: <"Foo">(tag: "Foo") => new <A>(args: Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => YieldableError & {
...;
} & Readonly<...>
TaggedError("Foo")<{5 (property) message: string
message: string6}> {}7
8// An error with _tag: "Bar"9class class BarError
BarError extends import Data
Data.const TaggedError: <"Bar">(tag: "Bar") => new <A>(args: Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => YieldableError & {
...;
} & Readonly<...>
TaggedError("Bar")<{10 (property) randomNumber: number
randomNumber: number11}> {}12
13const const program: Effect.Effect<string, never, never>
program = import Effect
Effect.const gen: <YieldWrap<Effect.Effect<number, never, never>> | YieldWrap<Effect.Effect<never, FooError, never>> | YieldWrap<Effect.Effect<never, BarError, never>>, string>(f: (resume: Effect.Adapter) => Generator<...>) => Effect.Effect<...> (+1 overload)
gen(function* () {14 const const n: number
n = yield* import Random
Random.const next: Effect.Effect<number, never, never>
Returns the next numeric value from the pseudo-random number generator.
next15 return const n: number
n > 0.516 ? "yay!"17 : const n: number
n < 0.218 ? yield* new constructor FooError<{
message: string;
}>(args: {
readonly message: string;
}): FooError
FooError({ (property) message: string
message: "Oh no!" })19 : yield* new constructor BarError<{
randomNumber: number;
}>(args: {
readonly randomNumber: number;
}): BarError
BarError({ (property) randomNumber: number
randomNumber: const n: number
n })20}).(method) Pipeable.pipe<Effect.Effect<string, FooError | BarError, never>, Effect.Effect<string, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<string, FooError | BarError, never>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(21 // Handle different tagged errors using catchTags22 import Effect
Effect.const catchTags: <FooError | BarError, {
Foo: (error: FooError) => Effect.Effect<string, never, never>;
Bar: (error: BarError) => Effect.Effect<string, never, never>;
}>(cases: {
...;
}) => <A, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+1 overload)
Recovers from the specified tagged errors.
catchTags({23 (property) Foo: (error: FooError) => Effect.Effect<string, never, never>
Foo: ((parameter) error: FooError
error) => import Effect
Effect.const succeed: <string>(value: string) => Effect.Effect<string, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed(`Foo error: ${(parameter) error: FooError
error.(property) message: string
message}`),24 (property) Bar: (error: BarError) => Effect.Effect<string, never, never>
Bar: ((parameter) error: BarError
error) => import Effect
Effect.const succeed: <string>(value: string) => Effect.Effect<string, never, never>
Creates an `Effect` that succeeds with the provided value.
Use this function to represent a successful computation that yields a value of type `A`.
The effect does not fail and does not require any environmental context.
succeed(`Bar error: ${(parameter) error: BarError
error.(property) randomNumber: number
randomNumber}`)25 })26)27
28import Effect
Effect.const runPromise: <string, never>(effect: Effect.Effect<string, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<string>
Executes an effect and returns a `Promise` that resolves with the result.
Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises.
If the effect fails, the returned Promise will be rejected with the error.
runPromise(const program: Effect.Effect<string, never, never>
program).(method) Promise<string>.then<void, void>(onfulfilled?: ((value: string) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => void | PromiseLike<void>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(namespace console
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`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
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:
```js
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
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
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)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
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()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log, namespace console
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`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
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:
```js
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
```
console.(method) Console.error(message?: any, ...optionalParams: any[]): void
Prints to `stderr` 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)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
```
If formatting elements (e.g. `%d`) are not found in the first string then
[`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options) is called on each argument and the
resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)
for more information.
error)29/*30Example Output (n < 0.2):31Foo error: Oh no!32*/