Errors in Effect often take the form of TaggedErrors, which extend the global Error class and have a unique string _tag along with additional custom properties:
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to use
Use when you want to write effectful code that looks and behaves like
synchronous code, while still handling asynchronous tasks, errors, and complex
control flow such as loops and conditions.
Generator functions work similarly to async/await but keep errors,
requirements, and interruption in the Effect type. You can yield* values
from effects and return the final result at the end.
Catches and handles specific errors by their _tag field, which is used as a
discriminator.
When to use
Use when you need to recover from one specific tagged error in an effect
error channel.
Details
The error type must have a readonly _tag field. catchTag matches that
field and only handles errors with the requested tag.
Gotchas
If the cause contains a defect, the handler is skipped and every typed error
is converted to a defect, preserving reason order and interrupts. An
interruption alongside a typed error does not prevent recovery.
While handling errors individually by their _tag is very easy to do by default, this level of granularity can become difficult to manage as the number of errors in your application grows. Often, you simply want to group errors into “categories” which you can discriminate against.
Outside of Effect, inheritance is the common pattern by which to implement this. Errors in the same category share a base class, and instanceof can be used to discriminate:
abstractclass
classCategoryA
CategoryAextends
var Error:ErrorConstructor
Error {}
abstractclass
classCategoryB
CategoryBextends
var Error:ErrorConstructor
Error {}
class
classFooError
FooErrorextends
classCategoryA
CategoryA {}
class
classBarError
BarErrorextends
classCategoryA
CategoryA {}
class
classBazError
BazErrorextends
classCategoryB
CategoryB {}
try {
// ...
} catch (
var error:unknown
error) {
if (
var error:unknown
errorinstanceof
classCategoryA
CategoryA) {
// do A
} elseif (
var error:unknown
errorinstanceof
classCategoryB
CategoryB) {
// do B
} else {
throw
var error:unknown
error;
}
}
However, this doesn’t work in Effect, because javascript does not support multiple inheritance, and we are already extending the TaggedError class from Effect! We could try to make an intermediate class that extends TaggedError that we can again extend from, but there’s a small problem: the types for TaggedError are straight up wizardy. Good luck making a fully functional generic wrapper for that.
Mixins, despite their fancy name, are remarkably simple. They are basically functions that take in a class and return a new class. Surprisingly, this is a pattern that has a whole page to itself in the official typescript docs.
There are a couple of cool things about this. First, everything is fully typed- typescript can infer the type of the class returned from the mixin and merge it with any class you extend from it, and we can even provide constraints on what classes can be passed into the mixin.
Also because a mixin is just a function, we can do all sorts of cool functional things like composition. I’m sure you’ve heard of “composition over inheritance” before and this pattern is that saying to a T.
Additionally, because mixins are just functions, we can use our favorite utility from Effect: pipe
import {
functionpipe<A>(a:A):A (+19overloads)
Pipes the value of an expression through a left-to-right sequence of
functions.
When to use
Use when you need to compose data-last functions into readable
transformation pipelines instead of method-style chains.
Details
Takes an initial value, passes it to the first function, then passes each
result to the next function in order. The final function result is returned.
Gotchas
Each function passed after the initial value must accept a single argument,
because pipe calls each step with only the previous result.
Example (Piping values through functions)
In this example, 1 is passed to the first function, and each result becomes
the input for the next function.
import { pipe } from"effect"
pipe(
1,
(n) => n +1,
(n) => n *2,
(n) =>`result: ${n}`
) // => "result: 4"
Example (Rewriting method chains with pipe)
The same transformation can be written with data-last functions.
import { Array, pipe } from"effect"
constnumbers= [1, 2, 3, 4]
constdouble= (n:number) => n *2
constgreaterThanFour= (n:number) => n >4
pipe(
numbers,
Array.map(double),
Array.filter(greaterThanFour)
) // => [6, 8]
@stability ― stable
@category ― combinators
@since ― 2.0.0
pipe } from"effect";
type
typeClass<T= {}> =new (...args:any[]) =>T
Class<
function (typeparameter) TintypeClass<T= {}>
T= {}> =new (...
args: any[]
args:any[]) =>
function (typeparameter) TintypeClass<T= {}>
T;
const
constMixin1: <TextendsClass>(Base:T) => {
new (...args:any[]): (Anonymousclass);
prototype:Mixin1<any>.(Anonymousclass);
} &T
Mixin1= <
function (typeparameter) Tin <TextendsClass>(Base:T): {
new (...args:any[]): (Anonymousclass);
prototype:Mixin1<any>.(Anonymousclass);
} &T
Textends
typeClass<T= {}> =new (...args:any[]) =>T
Class>(
typeBase: T extends Class
Base:
function (typeparameter) Tin <TextendsClass>(Base:T): {
new (...args:any[]): (Anonymousclass);
prototype:Mixin1<any>.(Anonymousclass);
} &T
T) =>
classextends
typeBase: T extends Class
Base {
function (Anonymousclass).one: boolean
one=true;
};
const
constMixin2: <TextendsClass>(Base:T) => {
new (...args:any[]): (Anonymousclass);
prototype:Mixin2<any>.(Anonymousclass);
} &T
Mixin2= <
function (typeparameter) Tin <TextendsClass>(Base:T): {
new (...args:any[]): (Anonymousclass);
prototype:Mixin2<any>.(Anonymousclass);
} &T
Textends
typeClass<T= {}> =new (...args:any[]) =>T
Class>(
typeBase: T extends Class
Base:
function (typeparameter) Tin <TextendsClass>(Base:T): {
new (...args:any[]): (Anonymousclass);
prototype:Mixin2<any>.(Anonymousclass);
} &T
T) =>
classextends
typeBase: T extends Class
Base {
function (Anonymousclass).two: boolean
two=true;
};
class
classMyError
MyErrorextends
pipe<ErrorConstructor, {
new (...args:any[]):Mixin1<ErrorConstructor>.(Anonymousclass);
prototype: Mixin1<any>.(Anonymous class);
} & ErrorConstructor, {
new (...args:any[]):Mixin2<{
new (...args:any[]):Mixin1<ErrorConstructor>.(Anonymousclass);
prototype:Mixin1<any>.(Anonymousclass);
} &ErrorConstructor>.(Anonymousclass);
prototype: Mixin2<...>.(Anonymous class);
} & {
new (...args:any[]):Mixin1<ErrorConstructor>.(Anonymousclass);
Use when you need a Predicate guard for property access on unknown
values with a simple structural object check.
Details
Uses the in operator and isObjectKeyword. This does not check property
value types.
Example (Guarding object properties)
import { Predicate } from"effect"
consthasName= Predicate.hasProperty("name")
constdata:unknown= { name: "Ada" }
if (hasName(data)) {
data.name // => "Ada"
}
@see ― isTagged
@see ― isObjectKeyword
@stability ― stable
@category ― guards
@since ― 2.0.0
hasProperty(
x: A
x,
sym: Category extends symbol
sym);
};
Next, using that guard, we can write a catchCategory function, which works just like catchTag, but on categories instead of tags. Just like catchTag, it properly narrows the output type to exclude caught errors:
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.
When to use
Use when you need to represent a lazy, composable workflow that can require
services, fail with a typed error, or succeed with a typed value.
Details
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.
@stability ― stable
@category ― models
@since ― 2.0.0
Effect<
function (typeparameter) Bin <E, Categoryextendssymbol, B, E2, R2>(category:Category, f: (error:Extract<E, Record<Category, any>>) =>Effect.Effect<B, E2, R2>): <A, R>(effect:Effect.Effect<A, E, R>) =>Effect.Effect<A|B, Exclude<E, Record<Category, any>> |E2, R|R2>
function (typeparameter) Ain <A, R>(effect:Effect.Effect<A, E, R>):Effect.Effect<A|B, Exclude<E, Record<Category, any>> |E2, R|R2>
A,
function (typeparameter) Rin <A, R>(effect:Effect.Effect<A, E, R>):Effect.Effect<A|B, Exclude<E, Record<Category, any>> |E2, R|R2>
R>(
effect: Effect.Effect<A, E, R>
effect:
import Effect
Effect.
interfaceEffect<outA, outE=never, outR=never>
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.
When to use
Use when you need to represent a lazy, composable workflow that can require
services, fail with a typed error, or succeed with a typed value.
Details
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.
@stability ― stable
@category ― models
@since ― 2.0.0
Effect<
function (typeparameter) Ain <A, R>(effect:Effect.Effect<A, E, R>):Effect.Effect<A|B, Exclude<E, Record<Category, any>> |E2, R|R2>
A,
function (typeparameter) Ein <E, Categoryextendssymbol, B, E2, R2>(category:Category, f: (error:Extract<E, Record<Category, any>>) =>Effect.Effect<B, E2, R2>): <A, R>(effect:Effect.Effect<A, E, R>) =>Effect.Effect<A|B, Exclude<E, Record<Category, any>> |E2, R|R2>
E,
function (typeparameter) Rin <A, R>(effect:Effect.Effect<A, E, R>):Effect.Effect<A|B, Exclude<E, Record<Category, any>> |E2, R|R2>
R>,
):
import Effect
Effect.
interfaceEffect<outA, outE=never, outR=never>
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.
When to use
Use when you need to represent a lazy, composable workflow that can require
services, fail with a typed error, or succeed with a typed value.
Details
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.
@stability ― stable
@category ― models
@since ― 2.0.0
Effect<
function (typeparameter) Ain <A, R>(effect:Effect.Effect<A, E, R>):Effect.Effect<A|B, Exclude<E, Record<Category, any>> |E2, R|R2>
A|
function (typeparameter) Bin <E, Categoryextendssymbol, B, E2, R2>(category:Category, f: (error:Extract<E, Record<Category, any>>) =>Effect.Effect<B, E2, R2>): <A, R>(effect:Effect.Effect<A, E, R>) =>Effect.Effect<A|B, Exclude<E, Record<Category, any>> |E2, R|R2>
B,
typeExclude<T, U> =TextendsU?never:T
Exclude from T those types that are assignable to U
Exclude<
function (typeparameter) Ein <E, Categoryextendssymbol, B, E2, R2>(category:Category, f: (error:Extract<E, Record<Category, any>>) =>Effect.Effect<B, E2, R2>): <A, R>(effect:Effect.Effect<A, E, R>) =>Effect.Effect<A|B, Exclude<E, Record<Category, any>> |E2, R|R2>
E,
typeRecord<Kextendskeyofany, T> = { [PinK]:T; }
Construct a type with a set of properties K of type T
Recovers from specific errors using a Predicate or Refinement.
When to use
Use when you need to recover from errors that match a condition.
Details
Use a Refinement for type narrowing or a Predicate for simple boolean
matching. Non-matching errors re-fail with the original cause. Defects and
interrupts are not caught.
Gotchas
If the cause contains a defect, the handler is skipped and every typed error
is converted to a defect, preserving reason order and interrupts. An
interruption alongside a typed error does not prevent recovery.
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.
When to use
Use when you need to represent a lazy, composable workflow that can require
services, fail with a typed error, or succeed with a typed value.
Details
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.
This pattern is pretty neat, decently practical and doesn’t impact any of the existing _tag ways of interacting with errors.
Check it out and let me know what you think. Here is a link to a full example in the Effect playground.
Thank you to Tim Smart for his feedback on this pattern and for authoring the catchCategory function.
UPDATE: Michael Arnaldi shared his own version of this pattern that works with string literals and has some other niceties like being able to catch multiple categories at once