Skip to content

Exit

Exit<A, E> 描述了运行 Effect 工作流的结果。

Exit<A, E> 有两种可能的状态:

  • Exit.Success:包含类型为 A 的成功值。
  • Exit.Failure:包含类型为 E 的失败 Cause

Exit 模块提供了两个主要函数来构造退出值:Exit.succeedExit.failCause。 这些函数以成功或失败的形式表示有效计算的结果。

Exit.succeed 创建一个表示成功结果的 Exit 值。 当您想要指示计算成功完成并提供结果值时,可以使用此函数。

示例(创建成功的 Exit)

import {
import Exit
Exit
} from "effect"
// 创建一个表示成功结果的 Exit,值为 42
//
// ┌─── Exit<number, never>
// ▼
const
const successExit: Exit.Exit<number, never>
successExit
=
import Exit
Exit
.
const succeed: <number>(value: number) => Exit.Exit<number, never>

Constructs a new Exit.Success containing the specified value of type A.

@since2.0.0

succeed
(42)
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const successExit: Exit.Exit<number, never>
successExit
)
// 输出: { _id: 'Exit', _tag: 'Success', value: 42 }

Exit.failCause 创建一个表示失败的 Exit 值。 失败使用 Cause 对象描述,它可以封装预期错误、缺陷、中断,甚至复合错误。

示例(创建失败的 Exit)

import {
import Exit
Exit
,
import Cause
Cause
} from "effect"
// 创建一个表示失败的 Exit,带有错误消息
//
// ┌─── Exit<never, string>
// ▼
const
const failureExit: Exit.Exit<never, string>
failureExit
=
import Exit
Exit
.
const failCause: <string>(cause: Cause.Cause<string>) => Exit.Exit<never, string>

Constructs a new Exit.Failure from the specified Cause of type E.

@since2.0.0

failCause
(
import Cause
Cause
.
const fail: <string>(error: string) => Cause.Cause<string>

Creates a Fail cause from an expected error.

Details

This function constructs a Cause carrying an error of type E. It's used when you want to represent a known or anticipated failure in your effectful computations.

@seeisFailure Check if a Cause contains a failure

@since2.0.0

fail
("Something went wrong"))
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const failureExit: Exit.Exit<never, string>
failureExit
)
/*
输出:
{
_id: 'Exit',
_tag: 'Failure',
cause: { _id: 'Cause', _tag: 'Fail', failure: 'Something went wrong' }
}
*/

您可以使用 Exit.match 函数处理 Exit 的不同结果。 此函数允许您提供两个单独的回调来处理 Effect 执行的成功和失败情况。

示例(匹配成功和失败状态)

import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Exit
Exit
,
import Cause
Cause
} from "effect"
// ┌─── Exit<number, never>
// ▼
const
const simulatedSuccess: Exit.Exit<number, never>
simulatedSuccess
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runSyncExit: <number, never>(effect: Effect.Effect<number, never, never>) => Exit.Exit<number, never>

Runs an effect synchronously and returns the result as an Exit type.

Details

This function executes the provided effect synchronously and returns an Exit type that encapsulates the outcome of the effect:

  • If the effect succeeds, the result is wrapped in a Success.
  • If the effect fails, it returns a Failure containing a Cause that explains the failure.

If the effect involves asynchronous operations, this function will return a Failure with a Die cause, indicating that it cannot resolve the effect synchronously. This makes the function suitable for use only with effects that are synchronous in nature.

When to Use

Use this function when:

  • You want to handle both success and failure outcomes in a structured way using the Exit type.
  • You are working with effects that are purely synchronous and do not involve asynchronous operations.
  • You need to debug or inspect failures, including their causes, in a detailed manner.

Avoid using this function for effects that involve asynchronous operations, as it will fail with a Die cause.

Example (Handling Results as Exit)

import { Effect } from "effect"
console.log(Effect.runSyncExit(Effect.succeed(1)))
// Output:
// {
// _id: "Exit",
// _tag: "Success",
// value: 1
// }
console.log(Effect.runSyncExit(Effect.fail("my error")))
// Output:
// {
// _id: "Exit",
// _tag: "Failure",
// cause: {
// _id: "Cause",
// _tag: "Fail",
// failure: "my error"
// }
// }

Example (Asynchronous Operation Resulting in Die)

import { Effect } from "effect"
console.log(Effect.runSyncExit(Effect.promise(() => Promise.resolve(1))))
// Output:
// {
// _id: 'Exit',
// _tag: 'Failure',
// cause: {
// _id: 'Cause',
// _tag: 'Die',
// defect: [Fiber #0 cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work] {
// fiber: [FiberRuntime],
// _tag: 'AsyncFiberException',
// name: 'AsyncFiberException'
// }
// }
// }

@since2.0.0

runSyncExit
(
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
(1))
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

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
(
import Exit
Exit
.
const match: <number, never, string, string>(self: Exit.Exit<number, never>, options: {
readonly onFailure: (cause: Cause.Cause<never>) => string;
readonly onSuccess: (a: number) => string;
}) => string (+1 overload)

@since2.0.0

match
(
const simulatedSuccess: Exit.Exit<number, never>
simulatedSuccess
, {
onFailure: (cause: Cause.Cause<never>) => string
onFailure
: (
cause: Cause.Cause<never>
cause
) =>
`以失败状态退出: ${
import Cause
Cause
.
const pretty: <never>(cause: Cause.Cause<never>, options?: {
readonly renderErrorCause?: boolean | undefined;
}) => string

Converts a Cause into a human-readable string.

Details

This function pretty-prints the entire Cause, including any failures, defects, and interruptions. It can be especially helpful for logging, debugging, or displaying structured errors to users.

You can optionally pass options to configure how the error cause is rendered. By default, it includes essential details of all errors in the Cause.

@seeprettyErrors Get a list of PrettyError objects instead of a single string.

@since2.0.0

pretty
(
cause: Cause.Cause<never>
cause
)}`,
onSuccess: (a: number) => string
onSuccess
: (
value: number
value
) => `以成功值退出: ${
value: number
value
}`
})
)
// 输出: "以成功值退出: 1"
// ┌─── Exit<never, string>
// ▼
const
const simulatedFailure: Exit.Exit<never, string>
simulatedFailure
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runSyncExit: <never, string>(effect: Effect.Effect<never, string, never>) => Exit.Exit<never, string>

Runs an effect synchronously and returns the result as an Exit type.

Details

This function executes the provided effect synchronously and returns an Exit type that encapsulates the outcome of the effect:

  • If the effect succeeds, the result is wrapped in a Success.
  • If the effect fails, it returns a Failure containing a Cause that explains the failure.

If the effect involves asynchronous operations, this function will return a Failure with a Die cause, indicating that it cannot resolve the effect synchronously. This makes the function suitable for use only with effects that are synchronous in nature.

When to Use

Use this function when:

  • You want to handle both success and failure outcomes in a structured way using the Exit type.
  • You are working with effects that are purely synchronous and do not involve asynchronous operations.
  • You need to debug or inspect failures, including their causes, in a detailed manner.

Avoid using this function for effects that involve asynchronous operations, as it will fail with a Die cause.

Example (Handling Results as Exit)

import { Effect } from "effect"
console.log(Effect.runSyncExit(Effect.succeed(1)))
// Output:
// {
// _id: "Exit",
// _tag: "Success",
// value: 1
// }
console.log(Effect.runSyncExit(Effect.fail("my error")))
// Output:
// {
// _id: "Exit",
// _tag: "Failure",
// cause: {
// _id: "Cause",
// _tag: "Fail",
// failure: "my error"
// }
// }

Example (Asynchronous Operation Resulting in Die)

import { Effect } from "effect"
console.log(Effect.runSyncExit(Effect.promise(() => Promise.resolve(1))))
// Output:
// {
// _id: 'Exit',
// _tag: 'Failure',
// cause: {
// _id: 'Cause',
// _tag: 'Die',
// defect: [Fiber #0 cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work] {
// fiber: [FiberRuntime],
// _tag: 'AsyncFiberException',
// name: 'AsyncFiberException'
// }
// }
// }

@since2.0.0

runSyncExit
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const failCause: <string>(cause: Cause.Cause<string>) => Effect.Effect<never, string, never>

Creates an Effect that fails with the specified Cause.

@since2.0.0

failCause
(
import Cause
Cause
.
const fail: <string>(error: string) => Cause.Cause<string>

Creates a Fail cause from an expected error.

Details

This function constructs a Cause carrying an error of type E. It's used when you want to represent a known or anticipated failure in your effectful computations.

@seeisFailure Check if a Cause contains a failure

@since2.0.0

fail
("error"))
)
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

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
(
import Exit
Exit
.
const match: <never, string, string, string>(self: Exit.Exit<never, string>, options: {
readonly onFailure: (cause: Cause.Cause<string>) => string;
readonly onSuccess: (a: never) => string;
}) => string (+1 overload)

@since2.0.0

match
(
const simulatedFailure: Exit.Exit<never, string>
simulatedFailure
, {
onFailure: (cause: Cause.Cause<string>) => string
onFailure
: (
cause: Cause.Cause<string>
cause
) =>
`以失败状态退出: ${
import Cause
Cause
.
const pretty: <string>(cause: Cause.Cause<string>, options?: {
readonly renderErrorCause?: boolean | undefined;
}) => string

Converts a Cause into a human-readable string.

Details

This function pretty-prints the entire Cause, including any failures, defects, and interruptions. It can be especially helpful for logging, debugging, or displaying structured errors to users.

You can optionally pass options to configure how the error cause is rendered. By default, it includes essential details of all errors in the Cause.

@seeprettyErrors Get a list of PrettyError objects instead of a single string.

@since2.0.0

pretty
(
cause: Cause.Cause<string>
cause
)}`,
onSuccess: (a: never) => string
onSuccess
: (
value: never
value
) => `以成功值退出: ${
value: never
value
}`
})
)
// 输出: "以失败状态退出: Error: error"

从概念上讲,Exit<A, E> 可以被认为是 Either<A, Cause<E>>。但是,Cause 类型不仅仅表示类型为 E 的预期错误。它包括:

  • 中断原因
  • 缺陷(意外错误)
  • 多个原因的组合

这使得 Cause 与简单的 Either 相比,能够捕获更丰富和更复杂的错误状态。

Exit 实际上是 Effect 的子类型。这意味着 Exit 值也可以被视为 Effect 值。

  • 本质上,Exit 是一个”常量计算”。
  • Effect.succeed 本质上与 Exit.succeed 相同。
  • Effect.failCauseExit.failCause 相同。