Skip to content

Unexpected Errors

There are situations where you may encounter unexpected errors, and you need to decide how to handle them. Effect provides functions to help you deal with such scenarios, allowing you to take appropriate actions when errors occur during the execution of your effects.

In the same way it is possible to leverage combinators such as Effect.fail to create values of type Effect<never, E, never> the Effect library provides tools to create defects.

Creating defects is a common necessity when dealing with errors from which it is not possible to recover from a business logic perspective, such as attempting to establish a connection that is refused after multiple retries.

In those cases terminating the execution of the effect and moving into reporting, through an output such as stdout or some external monitoring service, might be the best solution.

The following functions and combinators allow for termination of the effect and are often used to convert values of type Effect<A, E, R> into values of type Effect<A, never, R> allowing the programmer an escape hatch from having to handle and recover from errors for which there is no sensible way to recover.

The Effect.die function returns an effect that throws a specified error, while Effect.dieMessage throws a RuntimeException with a specified text message. These functions are useful for terminating a fiber when a defect, a critical and unexpected error, is detected in the code.

Example (Terminating on Division by Zero with Effect.die)

1
import {
import Effect
Effect
} from "effect"
2
3
const
const divide: (a: number, b: number) => Effect.Effect<number>
divide
= (
(parameter) a: number
a
: number,
(parameter) b: number
b
: number):
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> =>
4
(parameter) b: number
b
=== 0
5
?
import Effect
Effect
.
const die: (defect: unknown) => Effect.Effect<never>
die
(new
var Error: ErrorConstructor new (message?: string) => Error
Error
("Cannot divide by zero"))
6
:
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(
(parameter) a: number
a
/
(parameter) b: number
b
)
7
8
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 divide: (a: number, b: number) => Effect.Effect<number>
divide
(1, 0))
9
// throws Error: Cannot divide by zero

Example (Returning a RuntimeException with Effect.dieMessage)

1
import {
import Effect
Effect
} from "effect"
2
3
const
const divide: (a: number, b: number) => Effect.Effect<number>
divide
= (
(parameter) a: number
a
: number,
(parameter) b: number
b
: number):
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> =>
4
(parameter) b: number
b
=== 0
5
?
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
("Cannot divide by zero")
6
:
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(
(parameter) a: number
a
/
(parameter) b: number
b
)
7
8
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 divide: (a: number, b: number) => Effect.Effect<number>
divide
(1, 0))
9
// throws RuntimeException: Cannot divide by zero

The Effect.orDie function converts an effect’s failure into a termination of the fiber, removing the error from the type of the effect. It is useful when you encounter failures that you do not intend to handle or recover from.

Example (Converting Failure to Defect with Effect.orDie)

1
import {
import Effect
Effect
} from "effect"
2
3
const
const divide: (a: number, b: number) => Effect.Effect<number, Error>
divide
= (
(parameter) a: number
a
: number,
(parameter) b: number
b
: number):
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,
interface Error
Error
> =>
4
(parameter) b: number
b
=== 0
5
?
import Effect
Effect
.
const fail: <Error>(error: Error) => Effect.Effect<never, Error, 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
var Error: ErrorConstructor new (message?: string) => Error
Error
("Cannot divide by zero"))
6
:
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(
(parameter) a: number
a
/
(parameter) b: number
b
)
7
8
// ┌─── Effect<number, never, never>
9
// ▼
10
const
const program: Effect.Effect<number, never, never>
program
=
import Effect
Effect
.
const orDie: <number, Error, never>(self: Effect.Effect<number, Error, never>) => Effect.Effect<number, never, never>

Translates effect failure into death of the fiber, making all failures unchecked and not a part of the type of the effect.

orDie
(
const divide: (a: number, b: number) => Effect.Effect<number, Error>
divide
(1, 0))
11
12
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 program: Effect.Effect<number, never, never>
program
)
13
// throws Error: Cannot divide by zero

After using Effect.orDie, the error channel type of the program is never, meaning that the effect no longer handles failures, and will terminate the fiber when an error occurs.

Similar to Effect.orDie, the Effect.orDieWith function transforms an effect’s failure into a termination of the fiber using a specified mapping function. It allows you to customize the error message before terminating the fiber.

Example (Customizing Defect Message with Effect.orDieWith)

1
import {
import Effect
Effect
} from "effect"
2
3
const
const divide: (a: number, b: number) => Effect.Effect<number, Error>
divide
= (
(parameter) a: number
a
: number,
(parameter) b: number
b
: number):
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,
interface Error
Error
> =>
4
(parameter) b: number
b
=== 0
5
?
import Effect
Effect
.
const fail: <Error>(error: Error) => Effect.Effect<never, Error, 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
var Error: ErrorConstructor new (message?: string) => Error
Error
("Cannot divide by zero"))
6
:
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(
(parameter) a: number
a
/
(parameter) b: number
b
)
7
8
// ┌─── Effect<number, never, never>
9
// ▼
10
const
const program: Effect.Effect<number, never, never>
program
=
import Effect
Effect
.
const orDieWith: <number, Error, never>(self: Effect.Effect<number, Error, never>, f: (error: Error) => unknown) => Effect.Effect<number, never, never> (+1 overload)

Keeps none of the errors, and terminates the fiber with them, using the specified function to convert the `E` into a `Throwable`.

orDieWith
(
11
const divide: (a: number, b: number) => Effect.Effect<number, Error>
divide
(1, 0),
12
(
(parameter) error: Error
error
) => new
var Error: ErrorConstructor new (message?: string) => Error
Error
(`defect: ${
(parameter) error: Error
error
.
(property) Error.message: string
message
}`)
13
)
14
15
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 program: Effect.Effect<number, never, never>
program
)
16
// throws Error: defect: Cannot divide by zero

After using Effect.orDieWith, the error channel type of the program is never, just like with Effect.orDie.

There is no sensible way to recover from defects. The functions we’re about to discuss should be used only at the boundary between Effect and an external system, to transmit information on a defect for diagnostic or explanatory purposes.

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

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

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

By yielding an Exit, we gain the ability to “pattern match” on this type to handle both failure and success cases within the generator function.

Example (Catching Defects with Effect.exit)

1
import {
import Effect
Effect
,
import Cause
Cause
,
import Console
Console
,
import Exit
Exit
} from "effect"
2
3
// Simulating a runtime error
4
const
const task: Effect.Effect<never, never, never>
task
=
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
("Boom!")
5
6
const
const program: Effect.Effect<void, never, never>
program
=
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* () {
7
const
const exit: Exit.Exit<never, never>
exit
= yield*
import Effect
Effect
.
const exit: <never, never, never>(self: Effect.Effect<never, never, never>) => Effect.Effect<Exit.Exit<never, never>, never, never>
exit
(
const task: Effect.Effect<never, never, never>
task
)
8
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.

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

Returns `true` if the specified `Cause` is a `Die` type, `false` otherwise.

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

Returns `true` if the specified value is an `RuntimeException`, `false` otherwise.

isRuntimeException
(
const cause: Cause.Die
cause
.
(property) Die.defect: unknown
defect
)
13
) {
14
yield*
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(
15
`RuntimeException defect caught: ${
const cause: Cause.Die
cause
.
(property) Die.defect: Cause.RuntimeException
defect
.
(property) message: string
message
}`
16
)
17
} else {
18
yield*
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
("Unknown defect caught.")
19
}
20
}
21
})
22
23
// We get an Exit.Success because we caught all defects
24
import Effect
Effect
.
const runPromiseExit: <void, never>(effect: Effect.Effect<void, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Exit.Exit<void, never>>

Executes an effect and returns a `Promise` that resolves with an `Exit` describing the result. Use `runPromiseExit` when you need detailed information about the outcome of the effect, including success or failure, and you want to work with Promises.

runPromiseExit
(
const program: Effect.Effect<void, never, never>
program
).
(method) 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<...>

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
)
25
/*
26
Output:
27
RuntimeException defect caught: Boom!
28
{
29
_id: "Exit",
30
_tag: "Success",
31
value: undefined
32
}
33
*/

The Effect.catchAllDefect function allows you to recover from all defects using a provided function.

Example (Handling All Defects with Effect.catchAllDefect)

1
import {
import Effect
Effect
,
import Cause
Cause
,
import Console
Console
} from "effect"
2
3
// Simulating a runtime error
4
const
const task: Effect.Effect<never, never, never>
task
=
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
("Boom!")
5
6
const
const program: Effect.Effect<void, never, never>
program
=
import Effect
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 with provided function. **WARNING**: 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.

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

Returns `true` if the specified value is an `RuntimeException`, `false` otherwise.

isRuntimeException
(
(parameter) defect: unknown
defect
)) {
8
return
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(
9
`RuntimeException defect caught: ${
(parameter) defect: Cause.RuntimeException
defect
.
(property) message: string
message
}`
10
)
11
}
12
return
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
("Unknown defect caught.")
13
})
14
15
// We get an Exit.Success because we caught all defects
16
import Effect
Effect
.
const runPromiseExit: <void, never>(effect: Effect.Effect<void, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Exit<void, never>>

Executes an effect and returns a `Promise` that resolves with an `Exit` describing the result. Use `runPromiseExit` when you need detailed information about the outcome of the effect, including success or failure, and you want to work with Promises.

runPromiseExit
(
const program: Effect.Effect<void, never, never>
program
).
(method) 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<...>

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
)
17
/*
18
Output:
19
RuntimeException defect caught: Boom!
20
{
21
_id: "Exit",
22
_tag: "Success",
23
value: undefined
24
}
25
*/

It’s important to understand that Effect.catchAllDefect can only handle defects, not expected errors (such as those caused by Effect.fail) or interruptions in execution (such as when using Effect.interrupt).

A defect refers to an error that cannot be anticipated in advance, and there is no reliable way to respond to it. As a general rule, it’s recommended to let defects crash the application, as they often indicate serious issues that need to be addressed.

However, in some specific cases, such as when dealing with dynamically loaded plugins, a controlled recovery approach might be necessary. For example, if our application supports runtime loading of plugins and a defect occurs within a plugin, we may choose to log the defect and then reload only the affected plugin instead of crashing the entire application. This allows for a more resilient and uninterrupted operation of the application.

The Effect.catchSomeDefect function in Effect allows you to recover from specific defects using a provided partial function.

Example (Handling Specific Defects with Effect.catchSomeDefect)

1
import {
import Effect
Effect
,
import Cause
Cause
,
import Option
Option
,
import Console
Console
} from "effect"
2
3
// Simulating a runtime error
4
const
const task: Effect.Effect<never, never, never>
task
=
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
("Boom!")
5
6
const
const program: Effect.Effect<void, never, never>
program
=
import Effect
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<...> (+1 overload)

Recovers from some or all of the defects with provided partial function. **WARNING**: 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.

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

Returns `true` if the specified value is an `IllegalArgumentException`, `false` otherwise.

isIllegalArgumentException
(
(parameter) defect: unknown
defect
)) {
8
return
import Option
Option
.
const some: <Effect.Effect<void, never, never>>(value: Effect.Effect<void, never, never>) => Option.Option<Effect.Effect<void, never, never>>

Creates a new `Option` that wraps the given value.

some
(
9
import Console
Console
.
const log: (...args: ReadonlyArray<any>) => Effect.Effect<void>
log
(
10
`Caught an IllegalArgumentException defect: ${
(parameter) defect: Cause.IllegalArgumentException
defect
.
(property) message: string
message
}`
11
)
12
)
13
}
14
return
import Option
Option
.
const none: <never>() => Option.Option<never>

Creates a new `Option` that represents the absence of a value.

none
()
15
})
16
17
// Since we are only catching IllegalArgumentException
18
// we will get an Exit.Failure because we simulated a runtime error.
19
import Effect
Effect
.
const runPromiseExit: <void, never>(effect: Effect.Effect<void, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<Exit<void, never>>

Executes an effect and returns a `Promise` that resolves with an `Exit` describing the result. Use `runPromiseExit` when you need detailed information about the outcome of the effect, including success or failure, and you want to work with Promises.

runPromiseExit
(
const program: Effect.Effect<void, never, never>
program
).
(method) 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<...>

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
)
20
/*
21
Output:
22
{
23
_id: 'Exit',
24
_tag: 'Failure',
25
cause: {
26
_id: 'Cause',
27
_tag: 'Die',
28
defect: { _tag: 'RuntimeException' }
29
}
30
}
31
*/

It’s important to understand that catchSomeDefect can only handle defects, not expected errors (such as those caused by Effect.fail) or interruptions in execution (such as when using Effect.interrupt).