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.
Creating Unrecoverable Errors
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.
die
Creates an effect that terminates a fiber with a specified error.
Use Effect.die when encountering unexpected conditions in your code that should not be handled as regular errors but instead represent unrecoverable defects.
The Effect.die 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.
Example (Terminating on Division by Zero with a Specified Error)
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"
constdivide= (a:number, b:number) =>
b ===0
? Effect.die(newError("Cannot divide by zero"))
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
constprogram=divide(1, 0)
Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) Error: Cannot divide by zero
// ...stack trace...
@see ― dieSync for a variant that throws a specified error, evaluated lazily.
@see ― dieMessage for a variant that throws a RuntimeException with a message.
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)
Attaches a callback for only the rejection of the Promise.
@param ― onrejected The callback to execute when the Promise is rejected.
@returns ― A 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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
constcode=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.
@since ― v0.1.100
error)
13
/*
14
Output:
15
(FiberFailure) Error: Cannot divide by zero
16
...stack trace...
17
*/
dieMessage
Creates an effect that terminates a fiber with a RuntimeException containing the specified message.
Use Effect.dieMessage when you want to terminate a fiber due to an unrecoverable defect and include a clear explanation in the message.
The Effect.dieMessage 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.
Example (Terminating on Division by Zero with a Specified Message)
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"
constdivide= (a:number, b:number) =>
b ===0
? Effect.dieMessage("Cannot divide by zero")
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
constprogram=divide(1, 0)
Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) RuntimeException: Cannot divide by zero
// ...stack trace...
@see ― die for a variant that throws a specified error.
@see ― dieSync for a variant that throws a specified error, evaluated lazily.
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)
Attaches a callback for only the rejection of the Promise.
@param ― onrejected The callback to execute when the Promise is rejected.
@returns ― A 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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
constcode=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.
@since ― v0.1.100
error)
13
/*
14
Output:
15
(FiberFailure) RuntimeException: Cannot divide by zero
16
...stack trace...
17
*/
Converting Failures to Defects
orDie
Converts an effect’s failure into a fiber termination, removing the error from the effect’s type.
Use Effect.orDie when failures should be treated as unrecoverable defects and no error handling is required.
The Effect.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.
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>
// ▼
constfailure= Effect.fail(
newError("Operation failed due to network error")
)
@see ― succeed to create an effect that represents a successful value.
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"
constdivide= (a:number, b:number) =>
b ===0
? Effect.fail(newError("Cannot divide by zero"))
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
constprogram= Effect.orDie(divide(1, 0))
Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) Error: Cannot divide by zero
// ...stack trace...
@see ― orDieWith if you need to customize the error.
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)
Attaches a callback for only the rejection of the Promise.
@param ― onrejected The callback to execute when the Promise is rejected.
@returns ― A 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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
constcode=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.
@since ― v0.1.100
error)
13
/*
14
Output:
15
(FiberFailure) Error: Cannot divide by zero
16
...stack trace...
17
*/
orDieWith
Converts an effect’s failure into a fiber termination with a custom error.
Use Effect.orDieWith when failures should terminate the fiber as defects, and you want to customize the error for clarity or debugging purposes.
The Effect.orDieWith function behaves like Effect.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.
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>
// ▼
constfailure= Effect.fail(
newError("Operation failed due to network error")
)
@see ― succeed to create an effect that represents a successful value.
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"
constdivide= (a:number, b:number) =>
b ===0
? Effect.fail(newError("Cannot divide by zero"))
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
constprogram= Effect.orDieWith(
divide(1, 0),
(error) =>newError(`defect: ${error.message}`)
)
Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) Error: defect: Cannot divide by zero
// ...stack trace...
@see ― orDie if you don't need to customize the error.
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)
Attaches a callback for only the rejection of the Promise.
@param ― onrejected The callback to execute when the Promise is rejected.
@returns ― A 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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
constcode=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.
@since ― v0.1.100
error)
16
/*
17
Output:
18
(FiberFailure) Error: defect: Cannot divide by zero
19
...stack trace...
20
*/
Catching All Defects
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.
exit
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>
This means if you have an effect with the following type:
Effect<string, HttpError, never>
and you call Effect.exit on it, the type becomes:
Effect<Exit<string, HttpError>, never, never>
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.
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"
constdivide= (a:number, b:number) =>
b ===0
? Effect.dieMessage("Cannot divide by zero")
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
constprogram=divide(1, 0)
Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) RuntimeException: Cannot divide by zero
// ...stack trace...
@see ― die for a variant that throws a specified error.
@see ― dieSync for a variant that throws a specified error, evaluated lazily.
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.
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.
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
Attaches callbacks for the resolution and/or rejection of the Promise.
@param ― onfulfilled The callback to execute when the Promise is resolved.
@param ― onrejected The callback to execute when the Promise is rejected.
@returns ― A 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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
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).
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"
constdivide= (a:number, b:number) =>
b ===0
? Effect.dieMessage("Cannot divide by zero")
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
constprogram=divide(1, 0)
Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) RuntimeException: Cannot divide by zero
// ...stack trace...
@see ― die for a variant that throws a specified error.
@see ― dieSync for a variant that throws a specified error, evaluated lazily.
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.
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
Attaches callbacks for the resolution and/or rejection of the Promise.
@param ― onfulfilled The callback to execute when the Promise is resolved.
@param ― onrejected The callback to execute when the Promise is rejected.
@returns ― A 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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
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.
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"
constdivide= (a:number, b:number) =>
b ===0
? Effect.dieMessage("Cannot divide by zero")
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
constprogram=divide(1, 0)
Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) RuntimeException: Cannot divide by zero
// ...stack trace...
@see ― die for a variant that throws a specified error.
@see ― dieSync for a variant that throws a specified error, evaluated lazily.
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.
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
Attaches callbacks for the resolution and/or rejection of the Promise.
@param ― onfulfilled The callback to execute when the Promise is resolved.
@param ― onrejected The callback to execute when the Promise is rejected.
@returns ― A 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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).