Skip to content

Yieldable Errors

Yieldable Errors are special types of errors that can be yielded within a generator function used by Effect.gen. The unique feature of these errors is that you don’t need to use the Effect.fail API explicitly to handle them. They offer a more intuitive and convenient way to work with custom errors in your code.

The Data.Error constructor enables you to create a base yieldable error class. This class can be used to represent different types of errors in your code.

Example

1
import {
import Effect
Effect
,
import Data
Data
} from "effect"
2
3
class
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 }> {}
4
5
export 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* () {
6
// same as yield* Effect.fail(new MyError({ message: "Oh no!" })
7
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!" })
8
})
9
10
import Effect
Effect
.
const runPromiseExit: <void, MyError>(effect: Effect.Effect<void, MyError, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Exit<void, MyError>>

Runs an `Effect` workflow, returning a `Promise` which resolves with the `Exit` value of the workflow.

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
)
11
/*
12
Output:
13
{
14
_id: 'Exit',
15
_tag: 'Failure',
16
cause: { _id: 'Cause', _tag: 'Fail', failure: { message: 'Oh no!' } }
17
}
18
*/

The Data.TaggedError constructor is useful for creating tagged yieldable errors. These errors bear a distinct property named _tag, which acts as their unique identifier, allowing you to differentiate them from one another.

Example

1
import {
import Effect
Effect
,
import Data
Data
,
import Random
Random
} from "effect"
2
3
// An error with _tag: "Foo"
4
class
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
: string
6
}> {}
7
8
// An error with _tag: "Bar"
9
class
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
: number
11
}> {}
12
13
export const
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.

next
15
return
const n: number
n
> 0.5
16
? "yay!"
17
:
const n: number
n
< 0.2
18
? 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
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
({
22
(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>
succeed
(`Foo error: ${
(parameter) error: FooError
error
.
(property) message: string
message
}`),
23
(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>
succeed
(`Bar error: ${
(parameter) error: BarError
error
.
(property) randomNumber: number
randomNumber
}`)
24
})
25
)
26
27
import Effect
Effect
.
const runPromise: <string, never>(effect: Effect.Effect<string, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<string>

Runs an `Effect` workflow, returning a `Promise` which resolves with the result of the workflow or rejects with an 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
)
28
/*
29
Example Output (n < 0.2):
30
Foo error: Oh no!
31
*/

In this example, we create FooError and BarError classes with distinct tags (“Foo” and “Bar”). These tags help identify the type of error when handling errors in your code.