Skip to content

意外错误

有些情况下您可能会遇到意外错误,需要决定如何处理它们。Effect 提供函数来帮助您处理这种情况,允许您在 Effect 执行期间发生错误时采取适当的行动。

就像可以利用 Effect.fail 等组合子来创建 Effect<never, E, never> 类型的值一样,Effect 库提供了创建缺陷的工具。

当处理从业务逻辑角度无法恢复的错误时,创建缺陷是常见的需求,例如尝试建立在多次重试后被拒绝的连接。

在这些情况下,终止 Effect 的执行并转向报告(通过 stdout 或某些外部监控服务等输出)可能是最佳解决方案。

以下函数和组合子允许终止 Effect,通常用于将 Effect<A, E, R> 类型的值转换为 Effect<A, never, R> 类型的值,为程序员提供一个逃生舱口,无需处理和恢复没有合理恢复方式的错误。

创建一个使用指定错误终止纤程的 Effect。

当在代码中遇到不应作为常规错误处理,而是代表不可恢复缺陷的意外情况时,使用 Effect.die

Effect.die 函数用于发出缺陷信号,它代表代码中的关键和意外错误。调用时,它产生一个不处理错误而是终止纤程的 Effect。

结果 Effect 的错误通道类型为 never,表明它无法从此失败中恢复。

示例(使用指定错误在除零时终止)

import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const divide: (a: number, b: number) => Effect.Effect<number, never, never>
divide
= (
a: number
a
: number,
b: number
b
: number) =>
b: number
b
=== 0
?
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const die: (defect: unknown) => Effect.Effect<never>

Creates an effect that terminates a fiber with a specified error.

Details

This function is used to signal a defect, which represents a critical and unexpected error in the code. When invoked, it produces an effect that does not handle the error and instead terminates the fiber.

The error channel of the resulting effect is of type never, indicating that it cannot recover from this failure.

When to Use

Use this function when encountering unexpected conditions in your code that should not be handled as regular errors but instead represent unrecoverable defects.

Example (Terminating on Division by Zero with a Specified Error)

import { Effect } from "effect"
const divide = (a: number, b: number) =>
b === 0
? Effect.die(new Error("Cannot divide by zero"))
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
const program = divide(1, 0)
Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) Error: Cannot divide by zero
// ...stack trace...

@seedieSync for a variant that throws a specified error, evaluated lazily.

@seedieMessage for a variant that throws a RuntimeException with a message.

@since2.0.0

die
(new
var Error: ErrorConstructor
new (message?: string) => Error
Error
("Cannot divide by zero"))
:
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>

Creates an Effect that always succeeds with a given value.

When to Use

Use this function when you need an effect that completes successfully with a specific value without any errors or external dependencies.

Example (Creating a Successful Effect)

import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)

@seefail to create an effect that represents a failure.

@since2.0.0

succeed
(
a: number
a
/
b: number
b
)
// ┌─── Effect<number, never, never>
// ▼
const
const program: Effect.Effect<number, never, never>
program
=
const divide: (a: number, b: number) => Effect.Effect<number, never, never>
divide
(1, 0)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <number, never>(effect: Effect.Effect<number, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<number>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
const program: Effect.Effect<number, never, never>
program
).
Promise<number>.catch<void>(onrejected?: ((reason: any) => void | PromiseLike<void>) | null | undefined): Promise<number | void>

Attaches a callback for only the rejection of the Promise.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of the callback.

catch
(
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.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) (the arguments are all passed to util.format()).

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() is called on each argument and the resulting string values are concatenated. See util.format() for more information.

@sincev0.1.100

error
)
/*
Output:
(FiberFailure) Error: Cannot divide by zero
...stack trace...
*/

创建一个使用包含指定消息的 RuntimeException 终止纤程的 Effect。

当您想要由于不可恢复的缺陷而终止纤程并在消息中包含清晰解释时,使用 Effect.dieMessage

Effect.dieMessage 函数用于发出缺陷信号,代表代码中的关键和意外错误。调用时,它产生一个使用携带给定消息的 RuntimeException 终止纤程的 Effect。

结果 Effect 的错误通道类型为 never,表明它不处理或从错误中恢复。

示例(使用指定消息在除零时终止)

import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const divide: (a: number, b: number) => Effect.Effect<number, never, never>
divide
= (
a: number
a
: number,
b: number
b
: number) =>
b: number
b
=== 0
?
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Creates an effect that terminates a fiber with a RuntimeException containing the specified message.

Details

This function is used to signal a defect, representing a critical and unexpected error in the code. When invoked, it produces an effect that terminates the fiber with a RuntimeException carrying the given message.

The resulting effect has an error channel of type never, indicating it does not handle or recover from the error.

When to Use

Use this function when you want to terminate a fiber due to an unrecoverable defect and include a clear explanation in the message.

Example (Terminating on Division by Zero with a Specified Message)

import { Effect } from "effect"
const divide = (a: number, b: number) =>
b === 0
? Effect.dieMessage("Cannot divide by zero")
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
const program = divide(1, 0)
Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) RuntimeException: Cannot divide by zero
// ...stack trace...

@seedie for a variant that throws a specified error.

@seedieSync for a variant that throws a specified error, evaluated lazily.

@since2.0.0

dieMessage
("Cannot divide by zero")
:
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>

Creates an Effect that always succeeds with a given value.

When to Use

Use this function when you need an effect that completes successfully with a specific value without any errors or external dependencies.

Example (Creating a Successful Effect)

import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)

@seefail to create an effect that represents a failure.

@since2.0.0

succeed
(
a: number
a
/
b: number
b
)
// ┌─── Effect<number, never, never>
// ▼
const
const program: Effect.Effect<number, never, never>
program
=
const divide: (a: number, b: number) => Effect.Effect<number, never, never>
divide
(1, 0)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <number, never>(effect: Effect.Effect<number, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<number>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
const program: Effect.Effect<number, never, never>
program
).
Promise<number>.catch<void>(onrejected?: ((reason: any) => void | PromiseLike<void>) | null | undefined): Promise<number | void>

Attaches a callback for only the rejection of the Promise.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of the callback.

catch
(
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.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) (the arguments are all passed to util.format()).

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() is called on each argument and the resulting string values are concatenated. See util.format() for more information.

@sincev0.1.100

error
)
/*
Output:
(FiberFailure) RuntimeException: Cannot divide by zero
...stack trace...
*/

将 Effect 的失败转换为纤程终止,从 Effect 的类型中移除错误。

当失败应被视为不可恢复的缺陷且不需要错误处理时,使用 Effect.orDie

Effect.orDie 函数用于当您遇到不想处理或恢复的错误时。 它从 Effect 中移除错误类型,并确保任何失败都会终止纤程。 这对于将失败作为缺陷传播很有用,表明它们不应在 Effect 内处理。

示例(将错误作为缺陷传播)

import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const divide: (a: number, b: number) => Effect.Effect<never, Error, never> | Effect.Effect<number, never, never>
divide
= (
a: number
a
: number,
b: number
b
: number) =>
b: number
b
=== 0
?
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const fail: <Error>(error: Error) => Effect.Effect<never, Error, never>

Creates an Effect that represents a recoverable error.

When to Use

Use this function to explicitly signal an error in an Effect. The error will keep propagating unless it is handled. You can handle the error with functions like

catchAll

or

catchTag

.

Example (Creating a Failed Effect)

import { Effect } from "effect"
// ┌─── Effect<never, Error, never>
// ▼
const failure = Effect.fail(
new Error("Operation failed due to network error")
)

@seesucceed to create an effect that represents a successful value.

@since2.0.0

fail
(new
var Error: ErrorConstructor
new (message?: string) => Error
Error
("Cannot divide by zero"))
:
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>

Creates an Effect that always succeeds with a given value.

When to Use

Use this function when you need an effect that completes successfully with a specific value without any errors or external dependencies.

Example (Creating a Successful Effect)

import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)

@seefail to create an effect that represents a failure.

@since2.0.0

succeed
(
a: number
a
/
b: number
b
)
// ┌─── Effect<number, never, never>
// ▼
const
const program: Effect.Effect<number, never, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const orDie: <number, Error, never>(self: Effect.Effect<number, Error, never>) => Effect.Effect<number, never, never>

Converts an effect's failure into a fiber termination, removing the error from the effect's type.

Details

The orDie function is used when you encounter errors that you do not want to handle or recover from. It removes the error type from the effect and ensures that any failure will terminate the fiber. This is useful for propagating failures as defects, signaling that they should not be handled within the effect.

*When to Use

Use orDie when failures should be treated as unrecoverable defects and no error handling is required.

Example (Propagating an Error as a Defect)

import { Effect } from "effect"
const divide = (a: number, b: number) =>
b === 0
? Effect.fail(new Error("Cannot divide by zero"))
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
const program = Effect.orDie(divide(1, 0))
Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) Error: Cannot divide by zero
// ...stack trace...

@seeorDieWith if you need to customize the error.

@since2.0.0

orDie
(
const divide: (a: number, b: number) => Effect.Effect<never, Error, never> | Effect.Effect<number, never, never>
divide
(1, 0))
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <number, never>(effect: Effect.Effect<number, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<number>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
const program: Effect.Effect<number, never, never>
program
).
Promise<number>.catch<void>(onrejected?: ((reason: any) => void | PromiseLike<void>) | null | undefined): Promise<number | void>

Attaches a callback for only the rejection of the Promise.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of the callback.

catch
(
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.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) (the arguments are all passed to util.format()).

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() is called on each argument and the resulting string values are concatenated. See util.format() for more information.

@sincev0.1.100

error
)
/*
Output:
(FiberFailure) Error: Cannot divide by zero
...stack trace...
*/

将 Effect 的失败转换为使用自定义错误的纤程终止。

当失败应作为缺陷终止纤程,并且您想要为了清晰或调试目的自定义错误时,使用 Effect.orDieWith

Effect.orDieWith 函数的行为类似于 Effect.orDie,但它允许您提供一个映射函数在终止纤程之前转换错误。这对于当您想要在失败作为缺陷传播时包含更详细或用户友好的错误的情况很有用。

示例(自定义缺陷)

import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const divide: (a: number, b: number) => Effect.Effect<never, Error, never> | Effect.Effect<number, never, never>
divide
= (
a: number
a
: number,
b: number
b
: number) =>
b: number
b
=== 0
?
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const fail: <Error>(error: Error) => Effect.Effect<never, Error, never>

Creates an Effect that represents a recoverable error.

When to Use

Use this function to explicitly signal an error in an Effect. The error will keep propagating unless it is handled. You can handle the error with functions like

catchAll

or

catchTag

.

Example (Creating a Failed Effect)

import { Effect } from "effect"
// ┌─── Effect<never, Error, never>
// ▼
const failure = Effect.fail(
new Error("Operation failed due to network error")
)

@seesucceed to create an effect that represents a successful value.

@since2.0.0

fail
(new
var Error: ErrorConstructor
new (message?: string) => Error
Error
("Cannot divide by zero"))
:
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>

Creates an Effect that always succeeds with a given value.

When to Use

Use this function when you need an effect that completes successfully with a specific value without any errors or external dependencies.

Example (Creating a Successful Effect)

import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)

@seefail to create an effect that represents a failure.

@since2.0.0

succeed
(
a: number
a
/
b: number
b
)
// ┌─── Effect<number, never, never>
// ▼
const
const program: Effect.Effect<number, never, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const orDieWith: <number, Error, never>(self: Effect.Effect<number, Error, never>, f: (error: Error) => unknown) => Effect.Effect<number, never, never> (+1 overload)

Converts an effect's failure into a fiber termination with a custom error.

Details

The orDieWith function behaves like

orDie

, but it allows you to provide a mapping function to transform the error before terminating the fiber. This is useful for cases where you want to include a more detailed or user-friendly error when the failure is propagated as a defect.

When to Use

Use orDieWith when failures should terminate the fiber as defects, and you want to customize the error for clarity or debugging purposes.

Example (Customizing Defect)

import { Effect } from "effect"
const divide = (a: number, b: number) =>
b === 0
? Effect.fail(new Error("Cannot divide by zero"))
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
const program = Effect.orDieWith(
divide(1, 0),
(error) => new Error(`defect: ${error.message}`)
)
Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) Error: defect: Cannot divide by zero
// ...stack trace...

@seeorDie if you don't need to customize the error.

@since2.0.0

orDieWith
(
const divide: (a: number, b: number) => Effect.Effect<never, Error, never> | Effect.Effect<number, never, never>
divide
(1, 0),
(
error: Error
error
) => new
var Error: ErrorConstructor
new (message?: string) => Error
Error
(`defect: ${
error: Error
error
.
Error.message: string
message
}`)
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <number, never>(effect: Effect.Effect<number, never, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<number>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
const program: Effect.Effect<number, never, never>
program
).
Promise<number>.catch<void>(onrejected?: ((reason: any) => void | PromiseLike<void>) | null | undefined): Promise<number | void>

Attaches a callback for only the rejection of the Promise.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of the callback.

catch
(
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.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) (the arguments are all passed to util.format()).

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() is called on each argument and the resulting string values are concatenated. See util.format() for more information.

@sincev0.1.100

error
)
/*
Output:
(FiberFailure) Error: defect: Cannot divide by zero
...stack trace...
*/

没有合理的方法从缺陷中恢复。我们即将讨论的函数应该只在 Effect 和外部系统之间的边界使用,用于传输缺陷信息以进行诊断或解释目的。

Effect.exit 函数将 Effect<A, E, R> 转换为一个在 Exit 数据类型中封装潜在失败和成功的 Effect:

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

这意味着如果您有一个具有以下类型的 Effect:

Effect<string, HttpError, never>

并且您对其调用 Effect.exit,类型变为:

Effect<Exit<string, HttpError>, never, never>

结果 Effect 不能失败,因为潜在的失败现在在 ExitFailure 类型中表示。 返回的 Effect 的错误类型被指定为 never,确认该 Effect 被构造为不会失败。

通过产生一个 Exit,我们获得了在生成器函数中对此类型进行”模式匹配”以处理失败和成功情况的能力。

示例(使用 Effect.exit 捕获缺陷)

import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Cause
Cause
,
import Console
Console
,
import Exit
Exit
} from "effect"
// Simulating a runtime error
const
const task: Effect.Effect<never, never, never>
task
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Creates an effect that terminates a fiber with a RuntimeException containing the specified message.

Details

This function is used to signal a defect, representing a critical and unexpected error in the code. When invoked, it produces an effect that terminates the fiber with a RuntimeException carrying the given message.

The resulting effect has an error channel of type never, indicating it does not handle or recover from the error.

When to Use

Use this function when you want to terminate a fiber due to an unrecoverable defect and include a clear explanation in the message.

Example (Terminating on Division by Zero with a Specified Message)

import { Effect } from "effect"
const divide = (a: number, b: number) =>
b === 0
? Effect.dieMessage("Cannot divide by zero")
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
const program = divide(1, 0)
Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) RuntimeException: Cannot divide by zero
// ...stack trace...

@seedie for a variant that throws a specified error.

@seedieSync for a variant that throws a specified error, evaluated lazily.

@since2.0.0

dieMessage
("Boom!")
const
const program: Effect.Effect<void, never, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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<void, never, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
const
const exit: Exit.Exit<never, never>
exit
= yield*
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const exit: <never, never, never>(self: Effect.Effect<never, never, never>) => Effect.Effect<Exit.Exit<never, never>, never, never>

Encapsulates both success and failure of an Effect using the Exit type.

Details

This function converts an effect into one that always succeeds, wrapping its outcome in the Exit type. The Exit type provides explicit handling of both success (Exit.Success) and failure (Exit.Failure) cases, including defects (unrecoverable errors).

Unlike

either

or

option

, this function also encapsulates defects, which are typically unrecoverable and would otherwise terminate the effect. With the Exit type, defects are represented in Exit.Failure, allowing for detailed introspection and structured error handling.

This makes the resulting effect robust and incapable of direct failure (its error type is never). It is particularly useful for workflows where all outcomes, including unexpected defects, must be managed and analyzed.

Example

import { Effect, Cause, Console, Exit } from "effect"
// Simulating a runtime error
const task = Effect.dieMessage("Boom!")
const program = Effect.gen(function* () {
const exit = yield* Effect.exit(task)
if (Exit.isFailure(exit)) {
const cause = exit.cause
if (
Cause.isDieType(cause) &&
Cause.isRuntimeException(cause.defect)
) {
yield* Console.log(
`RuntimeException defect caught: ${cause.defect.message}`
)
} else {
yield* Console.log("Unknown failure caught.")
}
}
})
// We get an Exit.Success because we caught all failures
Effect.runPromiseExit(program).then(console.log)
// Output:
// RuntimeException defect caught: Boom!
// {
// _id: "Exit",
// _tag: "Success",
// value: undefined
// }

@seeoption for a version that uses Option instead.

@seeeither for a version that uses Either instead.

@since2.0.0

exit
(
const task: Effect.Effect<never, never, never>
task
)
if (
import Exit
Exit
.
const isFailure: <never, never>(self: Exit.Exit<never, never>) => self is Exit.Failure<never, never>

Returns true if the specified Exit is a Failure, false otherwise.

@since2.0.0

isFailure
(
const exit: Exit.Exit<never, never>
exit
)) {
const
const cause: Cause.Cause<never>
cause
=
const exit: Exit.Failure<never, never>
exit
.
Failure<never, never>.cause: Cause.Cause<never>
cause
if (
import Cause
Cause
.
const isDieType: <never>(self: Cause.Cause<never>) => self is Cause.Die

Checks if a Cause is a Die type.

@seedie Create a new Die cause

@since2.0.0

isDieType
(
const cause: Cause.Cause<never>
cause
) &&
import Cause
Cause
.
const isRuntimeException: (u: unknown) => u is Cause.RuntimeException

Checks if a given unknown value is a RuntimeException.

@since2.0.0

isRuntimeException
(
const cause: Cause.Die
cause
.
Die.defect: unknown
defect
)
) {
yield*
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>

@since2.0.0

log
(
`RuntimeException defect caught: ${
const cause: Cause.Die
cause
.
Die.defect: Cause.RuntimeException
defect
.
Error.message: string
message
}`
)
} else {
yield*
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>

@since2.0.0

log
("Unknown failure caught.")
}
}
})
// We get an Exit.Success because we caught all failures
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromiseExit: <void, never>(effect: Effect.Effect<void, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Exit.Exit<void, never>>

Runs an effect and returns a Promise that resolves to an Exit, representing the outcome.

Details

This function executes an effect and resolves to an Exit object. The Exit type provides detailed information about the result of the effect:

  • If the effect succeeds, the Exit will be of type Success and include the value produced by the effect.
  • If the effect fails, the Exit will be of type Failure and contain a Cause object, detailing the failure.

Using this function allows you to examine both successful results and failure cases in a unified way, while still leveraging Promise for handling the asynchronous behavior of the effect.

When to Use

Use this function when you need to understand the outcome of an effect, whether it succeeded or failed, and want to work with this result using Promise syntax. This is particularly useful when integrating with systems that rely on promises but need more detailed error handling than a simple rejection.

Example (Handling Results as Exit)

import { Effect } from "effect"
// Execute a successful effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.succeed(1)).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Success",
// value: 1
// }
// Execute a failing effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.fail("my error")).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Failure",
// cause: {
// _id: "Cause",
// _tag: "Fail",
// failure: "my error"
// }
// }

@since2.0.0

runPromiseExit
(
const program: Effect.Effect<void, never, never>
program
).
Promise<Exit<void, never>>.then<void, never>(onfulfilled?: ((value: Exit.Exit<void, never>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>

Attaches callbacks for the resolution and/or rejection of the Promise.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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
.
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) (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
)
/*
Output:
RuntimeException defect caught: Boom!
{
_id: "Exit",
_tag: "Success",
value: undefined
}
*/

Recovers from all defects using a provided recovery function.

Effect.catchAllDefect allows you to handle defects, which are unexpected errors that usually cause the program to terminate. This function lets you recover from these defects by providing a function that handles the error.

However, it does not handle expected errors (like those from Effect.fail) or execution interruptions (like those from Effect.interrupt).

Example (Handling All Defects)

import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Cause
Cause
,
import Console
Console
} from "effect"
// Simulating a runtime error
const
const task: Effect.Effect<never, never, never>
task
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Creates an effect that terminates a fiber with a RuntimeException containing the specified message.

Details

This function is used to signal a defect, representing a critical and unexpected error in the code. When invoked, it produces an effect that terminates the fiber with a RuntimeException carrying the given message.

The resulting effect has an error channel of type never, indicating it does not handle or recover from the error.

When to Use

Use this function when you want to terminate a fiber due to an unrecoverable defect and include a clear explanation in the message.

Example (Terminating on Division by Zero with a Specified Message)

import { Effect } from "effect"
const divide = (a: number, b: number) =>
b === 0
? Effect.dieMessage("Cannot divide by zero")
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
const program = divide(1, 0)
Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) RuntimeException: Cannot divide by zero
// ...stack trace...

@seedie for a variant that throws a specified error.

@seedieSync for a variant that throws a specified error, evaluated lazily.

@since2.0.0

dieMessage
("Boom!")
const
const program: Effect.Effect<void, never, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const catchAllDefect: <never, never, never, void, never, never>(self: Effect.Effect<never, never, never>, f: (defect: unknown) => Effect.Effect<void, never, never>) => Effect.Effect<void, never, never> (+1 overload)

Recovers from all defects using a provided recovery function.

When to Use

There is no sensible way to recover from defects. This method should be used only at the boundary between Effect and an external system, to transmit information on a defect for diagnostic or explanatory purposes.

Details

catchAllDefect allows you to handle defects, which are unexpected errors that usually cause the program to terminate. This function lets you recover from these defects by providing a function that handles the error. However, it does not handle expected errors (like those from

fail

) or execution interruptions (like those from

interrupt

).

When to Recover from Defects

Defects are unexpected errors that typically shouldn't be recovered from, as they often indicate serious issues. However, in some cases, such as dynamically loaded plugins, controlled recovery might be needed.

Example (Handling All Defects)

import { Effect, Cause, Console } from "effect"
// Simulating a runtime error
const task = Effect.dieMessage("Boom!")
const program = Effect.catchAllDefect(task, (defect) => {
if (Cause.isRuntimeException(defect)) {
return Console.log(
`RuntimeException defect caught: ${defect.message}`
)
}
return Console.log("Unknown defect caught.")
})
// We get an Exit.Success because we caught all defects
Effect.runPromiseExit(program).then(console.log)
// Output:
// RuntimeException defect caught: Boom!
// {
// _id: "Exit",
// _tag: "Success",
// value: undefined
// }

@since2.0.0

catchAllDefect
(
const task: Effect.Effect<never, never, never>
task
, (
defect: unknown
defect
) => {
if (
import Cause
Cause
.
const isRuntimeException: (u: unknown) => u is Cause.RuntimeException

Checks if a given unknown value is a RuntimeException.

@since2.0.0

isRuntimeException
(
defect: unknown
defect
)) {
return
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>

@since2.0.0

log
(
`RuntimeException defect caught: ${
defect: Cause.RuntimeException
defect
.
Error.message: string
message
}`
)
}
return
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>

@since2.0.0

log
("Unknown defect caught.")
})
// We get an Exit.Success because we caught all defects
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromiseExit: <void, never>(effect: Effect.Effect<void, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Exit<void, never>>

Runs an effect and returns a Promise that resolves to an Exit, representing the outcome.

Details

This function executes an effect and resolves to an Exit object. The Exit type provides detailed information about the result of the effect:

  • If the effect succeeds, the Exit will be of type Success and include the value produced by the effect.
  • If the effect fails, the Exit will be of type Failure and contain a Cause object, detailing the failure.

Using this function allows you to examine both successful results and failure cases in a unified way, while still leveraging Promise for handling the asynchronous behavior of the effect.

When to Use

Use this function when you need to understand the outcome of an effect, whether it succeeded or failed, and want to work with this result using Promise syntax. This is particularly useful when integrating with systems that rely on promises but need more detailed error handling than a simple rejection.

Example (Handling Results as Exit)

import { Effect } from "effect"
// Execute a successful effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.succeed(1)).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Success",
// value: 1
// }
// Execute a failing effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.fail("my error")).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Failure",
// cause: {
// _id: "Cause",
// _tag: "Fail",
// failure: "my error"
// }
// }

@since2.0.0

runPromiseExit
(
const program: Effect.Effect<void, never, never>
program
).
Promise<Exit<void, never>>.then<void, never>(onfulfilled?: ((value: Exit<void, never>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>

Attaches callbacks for the resolution and/or rejection of the Promise.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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
.
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) (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
)
/*
Output:
RuntimeException defect caught: Boom!
{
_id: "Exit",
_tag: "Success",
value: undefined
}
*/

Recovers from specific defects using a provided partial function.

Effect.catchSomeDefect allows you to handle specific defects, which are unexpected errors that can cause the program to stop. It uses a partial function to catch only certain defects and ignores others.

However, it does not handle expected errors (like those from Effect.fail) or execution interruptions (like those from Effect.interrupt).

The function provided to Effect.catchSomeDefect acts as a filter and a handler for defects:

  • It receives the defect as an input.
  • If the defect matches a specific condition (e.g., a certain error type), the function returns an Option.some containing the recovery logic.
  • If the defect does not match, the function returns Option.none, allowing the defect to propagate.

Example (Handling Specific Defects)

import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Cause
Cause
,
import Option

@since2.0.0

@since2.0.0

Option
,
import Console
Console
} from "effect"
// Simulating a runtime error
const
const task: Effect.Effect<never, never, never>
task
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Creates an effect that terminates a fiber with a RuntimeException containing the specified message.

Details

This function is used to signal a defect, representing a critical and unexpected error in the code. When invoked, it produces an effect that terminates the fiber with a RuntimeException carrying the given message.

The resulting effect has an error channel of type never, indicating it does not handle or recover from the error.

When to Use

Use this function when you want to terminate a fiber due to an unrecoverable defect and include a clear explanation in the message.

Example (Terminating on Division by Zero with a Specified Message)

import { Effect } from "effect"
const divide = (a: number, b: number) =>
b === 0
? Effect.dieMessage("Cannot divide by zero")
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
const program = divide(1, 0)
Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) RuntimeException: Cannot divide by zero
// ...stack trace...

@seedie for a variant that throws a specified error.

@seedieSync for a variant that throws a specified error, evaluated lazily.

@since2.0.0

dieMessage
("Boom!")
const
const program: Effect.Effect<void, never, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const catchSomeDefect: <never, never, never, void, never, never>(self: Effect.Effect<never, never, never>, pf: (defect: unknown) => Option.Option<Effect.Effect<void, never, never>>) => Effect.Effect<void, never, never> (+1 overload)

Recovers from specific defects using a provided partial function.

Details

catchSomeDefect allows you to handle specific defects, which are unexpected errors that can cause the program to stop. It uses a partial function to catch only certain defects and ignores others. The function does not handle expected errors (such as those caused by

fail

) or interruptions in execution (like those caused by

interrupt

).

This function provides a way to handle certain types of defects while allowing others to propagate and cause failure in the program.

Note: There is no sensible way to recover from defects. This method should be used only at the boundary between Effect and an external system, to transmit information on a defect for diagnostic or explanatory purposes.

How the Partial Function Works

The function provided to catchSomeDefect acts as a filter and a handler for defects:

  • It receives the defect as an input.
  • If the defect matches a specific condition (e.g., a certain error type), the function returns an Option.some containing the recovery logic.
  • If the defect does not match, the function returns Option.none, allowing the defect to propagate.

Example (Handling Specific Defects)

import { Effect, Cause, Option, Console } from "effect"
// Simulating a runtime error
const task = Effect.dieMessage("Boom!")
const program = Effect.catchSomeDefect(task, (defect) => {
if (Cause.isIllegalArgumentException(defect)) {
return Option.some(
Console.log(
`Caught an IllegalArgumentException defect: ${defect.message}`
)
)
}
return Option.none()
})
// Since we are only catching IllegalArgumentException
// we will get an Exit.Failure because we simulated a runtime error.
Effect.runPromiseExit(program).then(console.log)
// Output:
// {
// _id: 'Exit',
// _tag: 'Failure',
// cause: {
// _id: 'Cause',
// _tag: 'Die',
// defect: { _tag: 'RuntimeException' }
// }
// }

@since2.0.0

catchSomeDefect
(
const task: Effect.Effect<never, never, never>
task
, (
defect: unknown
defect
) => {
if (
import Cause
Cause
.
const isIllegalArgumentException: (u: unknown) => u is Cause.IllegalArgumentException

Checks if a given unknown value is an IllegalArgumentException.

@since2.0.0

isIllegalArgumentException
(
defect: unknown
defect
)) {
return
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <Effect.Effect<void, never, never>>(value: Effect.Effect<void, never, never>) => Option.Option<Effect.Effect<void, never, never>>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>

@since2.0.0

log
(
`Caught an IllegalArgumentException defect: ${
defect: Cause.IllegalArgumentException
defect
.
Error.message: string
message
}`
)
)
}
return
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <never>() => Option.Option<never>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()
})
// Since we are only catching IllegalArgumentException
// we will get an Exit.Failure because we simulated a runtime error.
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromiseExit: <void, never>(effect: Effect.Effect<void, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Exit<void, never>>

Runs an effect and returns a Promise that resolves to an Exit, representing the outcome.

Details

This function executes an effect and resolves to an Exit object. The Exit type provides detailed information about the result of the effect:

  • If the effect succeeds, the Exit will be of type Success and include the value produced by the effect.
  • If the effect fails, the Exit will be of type Failure and contain a Cause object, detailing the failure.

Using this function allows you to examine both successful results and failure cases in a unified way, while still leveraging Promise for handling the asynchronous behavior of the effect.

When to Use

Use this function when you need to understand the outcome of an effect, whether it succeeded or failed, and want to work with this result using Promise syntax. This is particularly useful when integrating with systems that rely on promises but need more detailed error handling than a simple rejection.

Example (Handling Results as Exit)

import { Effect } from "effect"
// Execute a successful effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.succeed(1)).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Success",
// value: 1
// }
// Execute a failing effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.fail("my error")).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Failure",
// cause: {
// _id: "Cause",
// _tag: "Fail",
// failure: "my error"
// }
// }

@since2.0.0

runPromiseExit
(
const program: Effect.Effect<void, never, never>
program
).
Promise<Exit<void, never>>.then<void, never>(onfulfilled?: ((value: Exit<void, never>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>

Attaches callbacks for the resolution and/or rejection of the Promise.

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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
.
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) (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
)
/*
Output:
{
_id: 'Exit',
_tag: 'Failure',
cause: {
_id: 'Cause',
_tag: 'Die',
defect: { _tag: 'RuntimeException' }
}
}
*/