Skip to content

Error Channel Operations

In Effect you can perform various operations on the error channel of effects. These operations allow you to transform, inspect, and handle errors in different ways. Let’s explore some of these operations.

The Effect.mapError function is used when you need to transform or modify an error produced by an effect, without affecting the success value. This can be helpful when you want to add extra information to the error or change its type.

Example (Mapping an Error)

Here, the error type changes from string to Error.

1
import {
import Effect
Effect
} from "effect"
2
3
// ┌─── Effect<number, string, never>
4
// ▼
5
const
const simulatedTask: Effect.Effect<number, string, never>
simulatedTask
=
import Effect
Effect
.
const fail: <string>(error: string) => Effect.Effect<never, string, never>

Creates an `Effect` that represents a recoverable error. This `Effect` does not succeed but instead fails with the provided error. The failure can be of any type, and will propagate through the effect pipeline unless handled. Use this function when you want to explicitly signal an error in an `Effect` computation. The failed effect can later be handled with functions like {@link catchAll } or {@link catchTag } .

fail
("Oh no!").
(method) Pipeable.pipe<Effect.Effect<never, string, never>, Effect.Effect<number, string, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<never, string, never>) => Effect.Effect<number, string, never>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect
Effect
.
const as: <number>(value: number) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<number, E, R> (+1 overload)

This function maps the success value of an `Effect` value to a specified constant value.

as
(1))
6
7
// ┌─── Effect<number, Error, never>
8
// ▼
9
const
const mapped: Effect.Effect<number, Error, never>
mapped
=
import Effect
Effect
.
const mapError: <number, string, never, Error>(self: Effect.Effect<number, string, never>, f: (e: string) => Error) => Effect.Effect<number, Error, never> (+1 overload)

Returns an effect with its error channel mapped using the specified function.

mapError
(
10
const simulatedTask: Effect.Effect<number, string, never>
simulatedTask
,
11
(
(parameter) message: string
message
) => new
var Error: ErrorConstructor new (message?: string) => Error
Error
(
(parameter) message: string
message
)
12
)

The Effect.mapBoth function allows you to apply transformations to both channels: the error channel and the success channel of an effect. It takes two map functions as arguments: one for the error channel and the other for the success channel.

Example (Mapping Both Success and Error)

1
import {
import Effect
Effect
} from "effect"
2
3
// ┌─── Effect<number, string, never>
4
// ▼
5
const
const simulatedTask: Effect.Effect<number, string, never>
simulatedTask
=
import Effect
Effect
.
const fail: <string>(error: string) => Effect.Effect<never, string, never>

Creates an `Effect` that represents a recoverable error. This `Effect` does not succeed but instead fails with the provided error. The failure can be of any type, and will propagate through the effect pipeline unless handled. Use this function when you want to explicitly signal an error in an `Effect` computation. The failed effect can later be handled with functions like {@link catchAll } or {@link catchTag } .

fail
("Oh no!").
(method) Pipeable.pipe<Effect.Effect<never, string, never>, Effect.Effect<number, string, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<never, string, never>) => Effect.Effect<number, string, never>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect
Effect
.
const as: <number>(value: number) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<number, E, R> (+1 overload)

This function maps the success value of an `Effect` value to a specified constant value.

as
(1))
6
7
// ┌─── Effect<boolean, Error, never>
8
// ▼
9
const
const modified: Effect.Effect<boolean, Error, never>
modified
=
import Effect
Effect
.
const mapBoth: <number, string, never, Error, boolean>(self: Effect.Effect<number, string, never>, options: { readonly onFailure: (e: string) => Error; readonly onSuccess: (a: number) => boolean; }) => Effect.Effect<...> (+1 overload)

Returns an effect whose failure and success channels have been mapped by the specified `onFailure` and `onSuccess` functions.

mapBoth
(
const simulatedTask: Effect.Effect<number, string, never>
simulatedTask
, {
10
(property) onFailure: (e: string) => Error
onFailure
: (
(parameter) message: string
message
) => new
var Error: ErrorConstructor new (message?: string) => Error
Error
(
(parameter) message: string
message
),
11
(property) onSuccess: (a: number) => boolean
onSuccess
: (
(parameter) n: number
n
) =>
(parameter) n: number
n
> 0
12
})

The Effect library provides several operators to filter values on the success channel based on a given predicate.

These operators offer different strategies for handling cases where the predicate fails:

APIDescription
filterOrFailThis operator filters the values on the success channel based on a predicate. If the predicate fails for any value, the original effect fails with an error.
filterOrDie / filterOrDieMessageThese operators also filter the values on the success channel based on a predicate. If the predicate fails for any value, the original effect terminates abruptly. The filterOrDieMessage variant allows you to provide a custom error message.
filterOrElseThis operator filters the values on the success channel based on a predicate. If the predicate fails for any value, an alternative effect is executed instead.

Example (Filtering Success Values)

1
import {
import Effect
Effect
,
import Random
Random
,
import Cause
Cause
} from "effect"
2
3
// Fail with a custom error if predicate is false
4
const
const task1: Effect.Effect<number, string, never>
task1
=
import Effect
Effect
.
const filterOrFail: <number, never, never, string>(self: Effect.Effect<number, never, never>, predicate: Predicate<number>, orFailWith: (a: number) => string) => Effect.Effect<number, string, never> (+7 overloads)

Filter the specified effect with the provided function, failing with specified error if the predicate fails. In addition to the filtering capabilities discussed earlier, you have the option to further refine and narrow down the type of the success channel by providing a [user-defined type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates). Let's explore this concept through an example:

filterOrFail
(
5
import Random
Random
.
const nextRange: (min: number, max: number) => Effect.Effect<number>

Returns the next numeric value in the specified range from the pseudo-random number generator.

nextRange
(-1, 1),
6
(
(parameter) n: number
n
) =>
(parameter) n: number
n
>= 0,
7
() => "random number is negative"
8
)
9
10
// Die with a custom exception if predicate is false
11
const
const task2: Effect.Effect<number, never, never>
task2
=
import Effect
Effect
.
const filterOrDie: <number, never, never>(self: Effect.Effect<number, never, never>, predicate: Predicate<number>, orDieWith: (a: number) => unknown) => Effect.Effect<number, never, never> (+3 overloads)

Filter the specified effect with the provided function, dying with specified defect if the predicate fails.

filterOrDie
(
12
import Random
Random
.
const nextRange: (min: number, max: number) => Effect.Effect<number>

Returns the next numeric value in the specified range from the pseudo-random number generator.

nextRange
(-1, 1),
13
(
(parameter) n: number
n
) =>
(parameter) n: number
n
>= 0,
14
() => new
import Cause
Cause
.
const IllegalArgumentException: new (message?: string | undefined) => Cause.IllegalArgumentException

Represents a checked exception which occurs when an invalid argument is provided to a method.

IllegalArgumentException
("random number is negative")
15
)
16
17
// Die with a custom error message if predicate is false
18
const
const task3: Effect.Effect<number, never, never>
task3
=
import Effect
Effect
.
const filterOrDieMessage: <number, never, never>(self: Effect.Effect<number, never, never>, predicate: Predicate<number>, message: string) => Effect.Effect<number, never, never> (+3 overloads)

Filter the specified effect with the provided function, dying with specified message if the predicate fails.

filterOrDieMessage
(
19
import Random
Random
.
const nextRange: (min: number, max: number) => Effect.Effect<number>

Returns the next numeric value in the specified range from the pseudo-random number generator.

nextRange
(-1, 1),
20
(
(parameter) n: number
n
) =>
(parameter) n: number
n
>= 0,
21
"random number is negative"
22
)
23
24
// Run an alternative effect if predicate is false
25
const
const task4: Effect.Effect<number, never, never>
task4
=
import Effect
Effect
.
const filterOrElse: <number, never, never, number, never, never>(self: Effect.Effect<number, never, never>, predicate: Predicate<number>, orElse: (a: number) => Effect.Effect<number, never, never>) => Effect.Effect<...> (+3 overloads)

Filters the specified effect with the provided function returning the value of the effect if it is successful, otherwise returns the value of `orElse`.

filterOrElse
(
26
import Random
Random
.
const nextRange: (min: number, max: number) => Effect.Effect<number>

Returns the next numeric value in the specified range from the pseudo-random number generator.

nextRange
(-1, 1),
27
(
(parameter) n: number
n
) =>
(parameter) n: number
n
>= 0,
28
() =>
const task3: Effect.Effect<number, never, never>
task3
29
)

It’s important to note that depending on the specific filtering operator used, the effect can either fail, terminate abruptly, or execute an alternative effect when the predicate fails. Choose the appropriate operator based on your desired error handling strategy and program logic.

The filtering APIs can also be combined with user-defined type guards to improve type safety and code clarity. This ensures that only valid types pass through.

Example (Using a Type Guard)

1
import {
import Effect
Effect
,
(alias) function pipe<A>(a: A): A (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
} from "effect"
2
3
// Define a user interface
4
interface
interface User
User
{
5
readonly
(property) User.name: string
name
: string
6
}
7
8
// Simulate an asynchronous authentication function
9
declare const
const auth: () => Promise<User | null>
auth
: () =>
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<
interface User
User
| null>
10
11
const
const program: Effect.Effect<string, Error, never>
program
=
(alias) pipe<Effect.Effect<User | null, never, never>, Effect.Effect<User, Error, never>, Effect.Effect<string, Error, never>>(a: Effect.Effect<...>, ab: (a: Effect.Effect<...>) => Effect.Effect<...>, bc: (b: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
(
12
import Effect
Effect
.
const promise: <User | null>(evaluate: (signal: AbortSignal) => PromiseLike<User | null>) => Effect.Effect<User | null, never, never>

Creates an `Effect` that represents an asynchronous computation guaranteed to succeed. The provided function (`thunk`) returns a `Promise` that should never reject. If the `Promise` does reject, the rejection is treated as a defect. An optional `AbortSignal` can be provided to allow for interruption of the wrapped `Promise` API.

promise
(() =>
const auth: () => Promise<User | null>
auth
()),
13
// Use filterOrFail with a custom type guard to ensure user is not null
14
import Effect
Effect
.
const filterOrFail: <User | null, User, Error>(refinement: Refinement<User | null, User>, orFailWith: (a: User | null) => Error) => <E, R>(self: Effect.Effect<...>) => Effect.Effect<...> (+7 overloads)

Filter the specified effect with the provided function, failing with specified error if the predicate fails. In addition to the filtering capabilities discussed earlier, you have the option to further refine and narrow down the type of the success channel by providing a [user-defined type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates). Let's explore this concept through an example:

filterOrFail
(
15
(
(parameter) user: User | null
user
):
(parameter) user: User | null
user
is
interface User
User
=>
(parameter) user: User | null
user
!== null, // Type guard
16
() => new
var Error: ErrorConstructor new (message?: string) => Error
Error
("Unauthorized")
17
),
18
// 'user' now has the type `User` (not `User | null`)
19
import Effect
Effect
.
const andThen: <User, string>(f: (a: User) => string) => <E, R>(self: Effect.Effect<User, E, R>) => Effect.Effect<string, E, R> (+3 overloads)

Executes a sequence of two actions, typically two `Effect`s, where the second action can depend on the result of the first action. The `that` action can take various forms: - a value - a function returning a value - a promise - a function returning a promise - an effect - a function returning an effect

andThen
((
(parameter) user: User
user
) =>
(parameter) user: User
user
.
(property) User.name: string
name
)
20
)

In the example above, a guard is used within the filterOrFail API to ensure that the user is of type User rather than User | null.

If you prefer, you can utilize a pre-made guard like Predicate.isNotNull for simplicity and consistency.

Similar to tapping for success values, Effect provides several operators for inspecting error values. These operators allow developers to observe failures or underlying issues without modifying the outcome.

Executes an effectful operation to inspect the failure of an effect without altering it.

Example (Inspecting Errors)

1
import {
import Effect
Effect
,
import Console
Console
} from "effect"
2
3
// Simulate a task that fails with an error
4
const
const task: Effect.Effect<number, string, never>
task
:
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never> namespace Effect

The `Effect` interface defines a value that lazily describes a workflow or job. The workflow requires some context `R`, and may fail with an error of type `E`, or succeed with a value of type `A`. `Effect` values model resourceful interaction with the outside world, including synchronous, asynchronous, concurrent, and parallel interaction. They use a fiber-based concurrency model, with built-in support for scheduling, fine-grained interruption, structured concurrency, and high scalability. To run an `Effect` value, you need a `Runtime`, which is a type that is capable of executing `Effect` values.

Effect
<number, string> =
import Effect
Effect
.
const fail: <string>(error: string) => Effect.Effect<never, string, never>

Creates an `Effect` that represents a recoverable error. This `Effect` does not succeed but instead fails with the provided error. The failure can be of any type, and will propagate through the effect pipeline unless handled. Use this function when you want to explicitly signal an error in an `Effect` computation. The failed effect can later be handled with functions like {@link catchAll } or {@link catchTag } .

fail
("NetworkError")
5
6
// Use tapError to log the error message when the task fails
7
const
const tapping: Effect.Effect<number, string, never>
tapping
=
import Effect
Effect
.
const tapError: <number, string, never, void, never, never>(self: Effect.Effect<number, string, never>, f: (e: string) => Effect.Effect<void, never, never>) => Effect.Effect<number, string, never> (+1 overload)

Executes an effectful operation to inspect the failure of an effect without altering it.

tapError
(
const task: Effect.Effect<number, string, never>
task
, (
(parameter) error: string
error
) =>
8
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(`expected error: ${
(parameter) error: string
error
}`)
9
)
10
11
import Effect
Effect
.
const runFork: <number, string>(effect: Effect.Effect<number, string, never>, options?: RunForkOptions) => RuntimeFiber<number, string>

Executes an effect and returns a `RuntimeFiber` that represents the running computation. Use `runFork` when you want to start an effect without blocking the current execution flow. It returns a fiber that you can observe, interrupt, or join as needed.

runFork
(
const tapping: Effect.Effect<number, string, never>
tapping
)
12
/*
13
Output:
14
expected error: NetworkError
15
*/

This function allows you to inspect errors that match a specific tag, helping you handle different error types more precisely.

Example (Inspecting Tagged Errors)

1
import {
import Effect
Effect
,
import Console
Console
} from "effect"
2
3
class
class NetworkError
NetworkError
{
4
readonly
(property) NetworkError._tag: "NetworkError"
_tag
= "NetworkError"
5
constructor(readonly
(property) NetworkError.statusCode: number
statusCode
: number) {}
6
}
7
8
class
class ValidationError
ValidationError
{
9
readonly
(property) ValidationError._tag: "ValidationError"
_tag
= "ValidationError"
10
constructor(readonly
(property) ValidationError.field: string
field
: string) {}
11
}
12
13
// Create a task that fails with a NetworkError
14
const
const task: Effect.Effect<number, NetworkError | ValidationError, never>
task
:
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never> namespace Effect

The `Effect` interface defines a value that lazily describes a workflow or job. The workflow requires some context `R`, and may fail with an error of type `E`, or succeed with a value of type `A`. `Effect` values model resourceful interaction with the outside world, including synchronous, asynchronous, concurrent, and parallel interaction. They use a fiber-based concurrency model, with built-in support for scheduling, fine-grained interruption, structured concurrency, and high scalability. To run an `Effect` value, you need a `Runtime`, which is a type that is capable of executing `Effect` values.

Effect
<number,
class NetworkError
NetworkError
|
class ValidationError
ValidationError
> =
15
import Effect
Effect
.
const fail: <NetworkError>(error: NetworkError) => Effect.Effect<never, NetworkError, never>

Creates an `Effect` that represents a recoverable error. This `Effect` does not succeed but instead fails with the provided error. The failure can be of any type, and will propagate through the effect pipeline unless handled. Use this function when you want to explicitly signal an error in an `Effect` computation. The failed effect can later be handled with functions like {@link catchAll } or {@link catchTag } .

fail
(new
constructor NetworkError(statusCode: number): NetworkError
NetworkError
(504))
16
17
// Use tapErrorTag to inspect only NetworkError types and log the status code
18
const
const tapping: Effect.Effect<number, NetworkError | ValidationError, never>
tapping
=
import Effect
Effect
.
const tapErrorTag: <number, NetworkError | ValidationError, never, "NetworkError", void, never, never>(self: Effect.Effect<number, NetworkError | ValidationError, never>, k: "NetworkError", f: (e: NetworkError) => Effect.Effect<...>) => Effect.Effect<...> (+1 overload)

Specifically inspects a failure with a particular tag, allowing focused error handling.

tapErrorTag
(
const task: Effect.Effect<number, NetworkError | ValidationError, never>
task
, "NetworkError", (
(parameter) error: NetworkError
error
) =>
19
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(`expected error: ${
(parameter) error: NetworkError
error
.
(property) NetworkError.statusCode: number
statusCode
}`)
20
)
21
22
import Effect
Effect
.
const runFork: <number, NetworkError | ValidationError>(effect: Effect.Effect<number, NetworkError | ValidationError, never>, options?: RunForkOptions) => RuntimeFiber<...>

Executes an effect and returns a `RuntimeFiber` that represents the running computation. Use `runFork` when you want to start an effect without blocking the current execution flow. It returns a fiber that you can observe, interrupt, or join as needed.

runFork
(
const tapping: Effect.Effect<number, NetworkError | ValidationError, never>
tapping
)
23
/*
24
Output:
25
expected error: 504
26
*/

This function inspects the complete cause of an error, including failures and defects.

Example (Inspecting Error Causes)

1
import {
import Effect
Effect
,
import Console
Console
} from "effect"
2
3
// Create a task that fails with a NetworkError
4
const
const task1: Effect.Effect<number, string, never>
task1
:
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never> namespace Effect

The `Effect` interface defines a value that lazily describes a workflow or job. The workflow requires some context `R`, and may fail with an error of type `E`, or succeed with a value of type `A`. `Effect` values model resourceful interaction with the outside world, including synchronous, asynchronous, concurrent, and parallel interaction. They use a fiber-based concurrency model, with built-in support for scheduling, fine-grained interruption, structured concurrency, and high scalability. To run an `Effect` value, you need a `Runtime`, which is a type that is capable of executing `Effect` values.

Effect
<number, string> =
import Effect
Effect
.
const fail: <string>(error: string) => Effect.Effect<never, string, never>

Creates an `Effect` that represents a recoverable error. This `Effect` does not succeed but instead fails with the provided error. The failure can be of any type, and will propagate through the effect pipeline unless handled. Use this function when you want to explicitly signal an error in an `Effect` computation. The failed effect can later be handled with functions like {@link catchAll } or {@link catchTag } .

fail
("NetworkError")
5
6
const
const tapping1: Effect.Effect<number, string, never>
tapping1
=
import Effect
Effect
.
const tapErrorCause: <number, string, never, void, never, never>(self: Effect.Effect<number, string, never>, f: (cause: Cause<string>) => Effect.Effect<void, never, never>) => Effect.Effect<...> (+1 overload)

Inspects the underlying cause of an effect's failure.

tapErrorCause
(
const task1: Effect.Effect<number, string, never>
task1
, (
(parameter) cause: Cause<string>
cause
) =>
7
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(`error cause: ${
(parameter) cause: Cause<string>
cause
}`)
8
)
9
10
import Effect
Effect
.
const runFork: <number, string>(effect: Effect.Effect<number, string, never>, options?: RunForkOptions) => RuntimeFiber<number, string>

Executes an effect and returns a `RuntimeFiber` that represents the running computation. Use `runFork` when you want to start an effect without blocking the current execution flow. It returns a fiber that you can observe, interrupt, or join as needed.

runFork
(
const tapping1: Effect.Effect<number, string, never>
tapping1
)
11
/*
12
Output:
13
error cause: Error: NetworkError
14
*/
15
16
// Simulate a severe failure in the system
17
const
const task2: Effect.Effect<number, string, never>
task2
:
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never> namespace Effect

The `Effect` interface defines a value that lazily describes a workflow or job. The workflow requires some context `R`, and may fail with an error of type `E`, or succeed with a value of type `A`. `Effect` values model resourceful interaction with the outside world, including synchronous, asynchronous, concurrent, and parallel interaction. They use a fiber-based concurrency model, with built-in support for scheduling, fine-grained interruption, structured concurrency, and high scalability. To run an `Effect` value, you need a `Runtime`, which is a type that is capable of executing `Effect` values.

Effect
<number, string> =
import Effect
Effect
.
const dieMessage: (message: string) => Effect.Effect<never>

Returns an effect that dies with a `RuntimeException` having the specified text message. This method can be used for terminating a fiber because a defect has been detected in the code.

dieMessage
(
18
"Something went wrong"
19
)
20
21
const
const tapping2: Effect.Effect<number, string, never>
tapping2
=
import Effect
Effect
.
const tapErrorCause: <number, string, never, void, never, never>(self: Effect.Effect<number, string, never>, f: (cause: Cause<string>) => Effect.Effect<void, never, never>) => Effect.Effect<...> (+1 overload)

Inspects the underlying cause of an effect's failure.

tapErrorCause
(
const task2: Effect.Effect<number, string, never>
task2
, (
(parameter) cause: Cause<string>
cause
) =>
22
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(`error cause: ${
(parameter) cause: Cause<string>
cause
}`)
23
)
24
25
import Effect
Effect
.
const runFork: <number, string>(effect: Effect.Effect<number, string, never>, options?: RunForkOptions) => RuntimeFiber<number, string>

Executes an effect and returns a `RuntimeFiber` that represents the running computation. Use `runFork` when you want to start an effect without blocking the current execution flow. It returns a fiber that you can observe, interrupt, or join as needed.

runFork
(
const tapping2: Effect.Effect<number, string, never>
tapping2
)
26
/*
27
Output:
28
error cause: RuntimeException: Something went wrong
29
... stack trace ...
30
*/

Specifically inspects non-recoverable failures or defects in an effect (i.e., one or more Die causes).

Example (Inspecting Defects)

1
import {
import Effect
Effect
,
import Console
Console
} from "effect"
2
3
// Simulate a task that fails with a recoverable error
4
const
const task1: Effect.Effect<number, string, never>
task1
:
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never> namespace Effect

The `Effect` interface defines a value that lazily describes a workflow or job. The workflow requires some context `R`, and may fail with an error of type `E`, or succeed with a value of type `A`. `Effect` values model resourceful interaction with the outside world, including synchronous, asynchronous, concurrent, and parallel interaction. They use a fiber-based concurrency model, with built-in support for scheduling, fine-grained interruption, structured concurrency, and high scalability. To run an `Effect` value, you need a `Runtime`, which is a type that is capable of executing `Effect` values.

Effect
<number, string> =
import Effect
Effect
.
const fail: <string>(error: string) => Effect.Effect<never, string, never>

Creates an `Effect` that represents a recoverable error. This `Effect` does not succeed but instead fails with the provided error. The failure can be of any type, and will propagate through the effect pipeline unless handled. Use this function when you want to explicitly signal an error in an `Effect` computation. The failed effect can later be handled with functions like {@link catchAll } or {@link catchTag } .

fail
("NetworkError")
5
6
// tapDefect won't log anything because NetworkError is not a defect
7
const
const tapping1: Effect.Effect<number, string, never>
tapping1
=
import Effect
Effect
.
const tapDefect: <number, string, never, void, never, never>(self: Effect.Effect<number, string, never>, f: (cause: Cause<never>) => Effect.Effect<void, never, never>) => Effect.Effect<...> (+1 overload)

Specifically inspects non-recoverable failures or defects in an effect (i.e., one or more `Die` causes).

tapDefect
(
const task1: Effect.Effect<number, string, never>
task1
, (
(parameter) cause: Cause<never>
cause
) =>
8
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(`defect: ${
(parameter) cause: Cause<never>
cause
}`)
9
)
10
11
import Effect
Effect
.
const runFork: <number, string>(effect: Effect.Effect<number, string, never>, options?: RunForkOptions) => RuntimeFiber<number, string>

Executes an effect and returns a `RuntimeFiber` that represents the running computation. Use `runFork` when you want to start an effect without blocking the current execution flow. It returns a fiber that you can observe, interrupt, or join as needed.

runFork
(
const tapping1: Effect.Effect<number, string, never>
tapping1
)
12
/*
13
No Output
14
*/
15
16
// Simulate a severe failure in the system
17
const
const task2: Effect.Effect<number, string, never>
task2
:
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never> namespace Effect

The `Effect` interface defines a value that lazily describes a workflow or job. The workflow requires some context `R`, and may fail with an error of type `E`, or succeed with a value of type `A`. `Effect` values model resourceful interaction with the outside world, including synchronous, asynchronous, concurrent, and parallel interaction. They use a fiber-based concurrency model, with built-in support for scheduling, fine-grained interruption, structured concurrency, and high scalability. To run an `Effect` value, you need a `Runtime`, which is a type that is capable of executing `Effect` values.

Effect
<number, string> =
import Effect
Effect
.
const dieMessage: (message: string) => Effect.Effect<never>

Returns an effect that dies with a `RuntimeException` having the specified text message. This method can be used for terminating a fiber because a defect has been detected in the code.

dieMessage
(
18
"Something went wrong"
19
)
20
21
// Log the defect using tapDefect
22
const
const tapping2: Effect.Effect<number, string, never>
tapping2
=
import Effect
Effect
.
const tapDefect: <number, string, never, void, never, never>(self: Effect.Effect<number, string, never>, f: (cause: Cause<never>) => Effect.Effect<void, never, never>) => Effect.Effect<...> (+1 overload)

Specifically inspects non-recoverable failures or defects in an effect (i.e., one or more `Die` causes).

tapDefect
(
const task2: Effect.Effect<number, string, never>
task2
, (
(parameter) cause: Cause<never>
cause
) =>
23
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(`defect: ${
(parameter) cause: Cause<never>
cause
}`)
24
)
25
26
import Effect
Effect
.
const runFork: <number, string>(effect: Effect.Effect<number, string, never>, options?: RunForkOptions) => RuntimeFiber<number, string>

Executes an effect and returns a `RuntimeFiber` that represents the running computation. Use `runFork` when you want to start an effect without blocking the current execution flow. It returns a fiber that you can observe, interrupt, or join as needed.

runFork
(
const tapping2: Effect.Effect<number, string, never>
tapping2
)
27
/*
28
Output:
29
defect: RuntimeException: Something went wrong
30
... stack trace ...
31
*/

Inspects both success and failure outcomes of an effect, performing different actions based on the result.

Example (Inspecting Both Success and Failure)

1
import {
import Effect
Effect
,
import Random
Random
,
import Console
Console
} from "effect"
2
3
// Simulate a task that might fail
4
const
const task: Effect.Effect<number, string, never>
task
=
import Effect
Effect
.
const filterOrFail: <number, never, never, string>(self: Effect.Effect<number, never, never>, predicate: Predicate<number>, orFailWith: (a: number) => string) => Effect.Effect<number, string, never> (+7 overloads)

Filter the specified effect with the provided function, failing with specified error if the predicate fails. In addition to the filtering capabilities discussed earlier, you have the option to further refine and narrow down the type of the success channel by providing a [user-defined type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates). Let's explore this concept through an example:

filterOrFail
(
5
import Random
Random
.
const nextRange: (min: number, max: number) => Effect.Effect<number>

Returns the next numeric value in the specified range from the pseudo-random number generator.

nextRange
(-1, 1),
6
(
(parameter) n: number
n
) =>
(parameter) n: number
n
>= 0,
7
() => "random number is negative"
8
)
9
10
// Use tapBoth to log both success and failure outcomes
11
const
const tapping: Effect.Effect<number, string, never>
tapping
=
import Effect
Effect
.
const tapBoth: <number, string, never, void, never, never, void, never, never>(self: Effect.Effect<number, string, never>, options: { readonly onFailure: (e: string) => Effect.Effect<void, never, never>; readonly onSuccess: (a: number) => Effect.Effect<...>; }) => Effect.Effect<...> (+1 overload)

Inspects both success and failure outcomes of an effect, performing different actions based on the result.

tapBoth
(
const task: Effect.Effect<number, string, never>
task
, {
12
(property) onFailure: (e: string) => Effect.Effect<void, never, never>
onFailure
: (
(parameter) error: string
error
) =>
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(`failure: ${
(parameter) error: string
error
}`),
13
(property) onSuccess: (a: number) => Effect.Effect<void, never, never>
onSuccess
: (
(parameter) randomNumber: number
randomNumber
) =>
14
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(`random number: ${
(parameter) randomNumber: number
randomNumber
}`)
15
})
16
17
import Effect
Effect
.
const runFork: <number, string>(effect: Effect.Effect<number, string, never>, options?: RunForkOptions) => RuntimeFiber<number, string>

Executes an effect and returns a `RuntimeFiber` that represents the running computation. Use `runFork` when you want to start an effect without blocking the current execution flow. It returns a fiber that you can observe, interrupt, or join as needed.

runFork
(
const tapping: Effect.Effect<number, string, never>
tapping
)
18
/*
19
Example Output:
20
failure: random number is negative
21
*/

The Effect.either function transforms an Effect<A, E, R> into an effect that encapsulates both potential failure and success within an Either data type:

Effect<A, E, R> -> Effect<Either<A, E>, never, R>

This means if you have an effect with the following type:

Effect<string, HttpError, never>

and you call Effect.either on it, the type becomes:

Effect<Either<string, HttpError>, never, never>

The resulting effect cannot fail because the potential failure is now represented within the Either’s Left type. The error type of the returned Effect is specified as never, confirming that the effect is structured to not fail.

This function becomes especially useful when recovering from effects that may fail when using Effect.gen:

Example (Using Effect.either to Handle Errors)

1
import {
import Effect
Effect
,
import Either
Either
,
import Console
Console
} from "effect"
2
3
// Simulate a task that fails
4
//
5
// ┌─── Either<number, string, never>
6
// ▼
7
const
const program: Effect.Effect<number, string, never>
program
=
import Effect
Effect
.
const fail: <string>(error: string) => Effect.Effect<never, string, never>

Creates an `Effect` that represents a recoverable error. This `Effect` does not succeed but instead fails with the provided error. The failure can be of any type, and will propagate through the effect pipeline unless handled. Use this function when you want to explicitly signal an error in an `Effect` computation. The failed effect can later be handled with functions like {@link catchAll } or {@link catchTag } .

fail
("Oh uh!").
(method) Pipeable.pipe<Effect.Effect<never, string, never>, Effect.Effect<number, string, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<never, string, never>) => Effect.Effect<number, string, never>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect
Effect
.
const as: <number>(value: number) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<number, E, R> (+1 overload)

This function maps the success value of an `Effect` value to a specified constant value.

as
(2))
8
9
// ┌─── Either<number, never, never>
10
// ▼
11
const
const recovered: Effect.Effect<number, never, never>
recovered
=
import Effect
Effect
.
const gen: <YieldWrap<Effect.Effect<void, never, never>>, number>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<void, never, never>>, number, never>) => Effect.Effect<...> (+1 overload)
gen
(function* () {
12
// ┌─── Either<number, string>
13
// ▼
14
const
const failureOrSuccess: Either.Either<number, string>
failureOrSuccess
= yield*
import Effect
Effect
.
const either: <number, string, never>(self: Effect.Effect<number, string, never>) => Effect.Effect<Either.Either<number, string>, never, never>

Returns an effect whose failure and success have been lifted into an `Either`. The resulting effect cannot fail, because the failure case has been exposed as part of the `Either` success case. This method is useful for recovering from effects that may fail. The error parameter of the returned `Effect` is `never`, since it is guaranteed the effect does not model failure.

either
(
const program: Effect.Effect<number, string, never>
program
)
15
if (
import Either
Either
.
const isLeft: <number, string>(self: Either.Either<number, string>) => self is Either.Left<string, number>

Determine if a `Either` is a `Left`.

isLeft
(
const failureOrSuccess: Either.Either<number, string>
failureOrSuccess
)) {
16
const
const error: string
error
=
const failureOrSuccess: Either.Left<string, number>
failureOrSuccess
.
(property) Left<string, number>.left: string
left
17
yield*
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(`failure: ${
const error: string
error
}`)
18
return 0
19
} else {
20
const
const value: number
value
=
const failureOrSuccess: Either.Right<string, number>
failureOrSuccess
.
(property) Right<string, number>.right: number
right
21
yield*
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(`success: ${
const value: number
value
}`)
22
return
const value: number
value
23
}
24
})
25
26
import Effect
Effect
.
const runPromise: <number, never>(effect: Effect.Effect<number, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<number>

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 recovered: Effect.Effect<number, never, never>
recovered
).
(method) Promise<number>.then<void, never>(onfulfilled?: ((value: number) => 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) globalThis.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
)
27
/*
28
Output:
29
failure: Oh uh!
30
0
31
*/

You can use the Effect.cause function to expose the cause of an effect, which is a more detailed representation of failures, including error messages and defects.

Example (Logging the Cause of Failure)

1
import {
import Effect
Effect
,
import Console
Console
} from "effect"
2
3
// ┌─── Effect<number, string, never>
4
// ▼
5
const
const program: Effect.Effect<number, string, never>
program
=
import Effect
Effect
.
const fail: <string>(error: string) => Effect.Effect<never, string, never>

Creates an `Effect` that represents a recoverable error. This `Effect` does not succeed but instead fails with the provided error. The failure can be of any type, and will propagate through the effect pipeline unless handled. Use this function when you want to explicitly signal an error in an `Effect` computation. The failed effect can later be handled with functions like {@link catchAll } or {@link catchTag } .

fail
("Oh uh!").
(method) Pipeable.pipe<Effect.Effect<never, string, never>, Effect.Effect<number, string, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<never, string, never>) => Effect.Effect<number, string, never>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect
Effect
.
const as: <number>(value: number) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<number, E, R> (+1 overload)

This function maps the success value of an `Effect` value to a specified constant value.

as
(2))
6
7
// ┌─── Effect<void, never, never>
8
// ▼
9
const
const recovered: Effect.Effect<void, never, never>
recovered
=
import Effect
Effect
.
const gen: <YieldWrap<Effect.Effect<void, never, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<void, never, never>>, void, never>) => Effect.Effect<...> (+1 overload)
gen
(function* () {
10
const
const cause: Cause<string>
cause
= yield*
import Effect
Effect
.
const cause: <number, string, never>(self: Effect.Effect<number, string, never>) => Effect.Effect<Cause<string>, never, never>

Returns an effect that succeeds with the cause of failure of this effect, or `Cause.empty` if the effect did succeed.

cause
(
const program: Effect.Effect<number, string, never>
program
)
11
yield*
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(
const cause: Cause<string>
cause
)
12
})

The Effect.merge function allows you to combine the error channel with the success channel. This results in an effect that never fails; instead, both successes and errors are handled as values in the success channel.

Example (Combining Error and Success Channels)

1
import {
import Effect
Effect
} from "effect"
2
3
// ┌─── Effect<number, string, never>
4
// ▼
5
const
const program: Effect.Effect<number, string, never>
program
=
import Effect
Effect
.
const fail: <string>(error: string) => Effect.Effect<never, string, never>

Creates an `Effect` that represents a recoverable error. This `Effect` does not succeed but instead fails with the provided error. The failure can be of any type, and will propagate through the effect pipeline unless handled. Use this function when you want to explicitly signal an error in an `Effect` computation. The failed effect can later be handled with functions like {@link catchAll } or {@link catchTag } .

fail
("Oh uh!").
(method) Pipeable.pipe<Effect.Effect<never, string, never>, Effect.Effect<number, string, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<never, string, never>) => Effect.Effect<number, string, never>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect
Effect
.
const as: <number>(value: number) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<number, E, R> (+1 overload)

This function maps the success value of an `Effect` value to a specified constant value.

as
(2))
6
7
// ┌─── Effect<number | string, never, never>
8
// ▼
9
const
const recovered: Effect.Effect<string | number, never, never>
recovered
=
import Effect
Effect
.
const merge: <number, string, never>(self: Effect.Effect<number, string, never>) => Effect.Effect<string | number, never, never>

Returns a new effect where the error channel has been merged into the success channel to their common combined type.

merge
(
const program: Effect.Effect<number, string, never>
program
)

The Effect.flip function allows you to switch the error and success channels of an effect. This means that what was previously a success becomes the error, and vice versa.

Example (Swapping Error and Success Channels)

1
import {
import Effect
Effect
} from "effect"
2
3
// ┌─── Effect<number, string, never>
4
// ▼
5
const
const program: Effect.Effect<number, string, never>
program
=
import Effect
Effect
.
const fail: <string>(error: string) => Effect.Effect<never, string, never>

Creates an `Effect` that represents a recoverable error. This `Effect` does not succeed but instead fails with the provided error. The failure can be of any type, and will propagate through the effect pipeline unless handled. Use this function when you want to explicitly signal an error in an `Effect` computation. The failed effect can later be handled with functions like {@link catchAll } or {@link catchTag } .

fail
("Oh uh!").
(method) Pipeable.pipe<Effect.Effect<never, string, never>, Effect.Effect<number, string, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<never, string, never>) => Effect.Effect<number, string, never>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect
Effect
.
const as: <number>(value: number) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<number, E, R> (+1 overload)

This function maps the success value of an `Effect` value to a specified constant value.

as
(2))
6
7
// ┌─── Effect<string, number, never>
8
// ▼
9
const
const flipped: Effect.Effect<string, number, never>
flipped
=
import Effect
Effect
.
const flip: <number, string, never>(self: Effect.Effect<number, string, never>) => Effect.Effect<string, number, never>

Returns an effect that swaps the error/success cases. This allows you to use all methods on the error channel, possibly before flipping back.

flip
(
const program: Effect.Effect<number, string, never>
program
)