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:

class
class FooError
FooError
extends
import S
S
.
const TaggedError: <FooError, {}>(identifier?: string) => {
<Tag, Fields>(tag: Tag, fields: Fields, annotations?: S.Annotations.Declaration<FooError, readonly [S.TaggedStruct<Tag, Fields>]> | undefined): S.Class<FooError, S.TaggedStruct<Tag, Fields>, YieldableError>;
<Tag, S>(tag: Tag, schema: S, annotations?: S.Annotations.Declaration<FooError, readonly [S.Struct<{ [K in keyof ({
readonly _tag: S.tag<Tag>;
} & S["fields"])]: ({
readonly _tag: S.tag<Tag>;
} & S["fields"])[K]; }>]> | undefined): S.Class<...>;
}

Defines a schema-backed yieldable error class with an automatically populated _tag field.

When to use

Use to define typed errors that are schema validated, yielded in Effect.gen, and matched as tagged union members.

Example (Defining a tagged error class)

import { Effect, Schema } from "effect"
class NotFound extends Schema.TaggedError<NotFound>()("NotFound", {
id: Schema.Number
}) {}
const program = Effect.gen(function*() {
yield* new NotFound({ id: 42 })
})
const error = await Effect.runPromise(Effect.flip(program))
error._tag // => "NotFound"
error.id // => 42

@stability ― stable

@category ― constructors

@since ― 3.10.0

TaggedError
<
class FooError
FooError
>()("FooError", {
bar: S.String
bar
:
import S
S
.
const String: S.String

Type-level representation of

String

.

Schema for string values. Validates that the input is typeof "string".

@stability ― stable

@category ― models

@since ― 4.0.0

@stability ― stable

@category ― schemas

@since ― 4.0.0

String
,
}) {}
const
const foo: Effect.Effect<void, FooError, never>
foo
=
import Effect
Effect
.
const gen: <Effect.Effect<never, FooError, never>, void>(f: () => Generator<Effect.Effect<never, FooError, never>, void, never>) => Effect.Effect<void, FooError, never> (+1 overload)

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.

Example (Sequencing effects with generators)

import { Data, Effect } from "effect"
class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {}
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, DiscountRateError> =>
discountRate === 0
? Effect.fail(new DiscountRateError())
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function*() {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})
await Effect.runPromise(program) // => "Final amount to charge: 96"

@stability ― stable

@category ― constructors

@since ― 2.0.0

gen
(function* () {
if (
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.random(): number

Returns a pseudorandom number between 0 and 1.

random
() > 0.5) {
yield*
import Effect
Effect
.
const fail: <FooError>(error: FooError) => Effect.Effect<never, FooError, never>

Creates an Effect that represents a recoverable error.

When to use

Use to explicitly signal a recoverable error in an Effect.

Details

The error keeps propagating unless it is handled. You can handle tagged errors with functions like

catchTag

or

catchTags

.

Example (Creating a failed effect)

import { Data, Effect } from "effect"
class OperationFailedError extends Data.TaggedError("OperationFailedError")<{}> {}
// ┌─── Effect<never, OperationFailedError, never>
// ▼
const failure = Effect.fail(
new OperationFailedError()
)
Effect.runSync(Effect.flip(failure))._tag // => "OperationFailedError"

@see ― succeed to create an effect that represents a successful value.

@stability ― stable

@category ― constructors

@since ― 2.0.0

fail
(new
constructor FooError(props: {
readonly bar: string;
readonly _tag?: "FooError" | undefined;
}, options?: S.MakeOptions | undefined): FooError
FooError
({
bar: string
bar
: "jfdsk" }));
}
});
const
const handled: Effect.Effect<void, never, never>
handled
=
const foo: Effect.Effect<void, FooError, never>
foo
.
Pipeable.pipe<Effect.Effect<void, FooError, never>, Effect.Effect<void, never, never>>(this: Effect.Effect<void, FooError, never>, ab: (_: Effect.Effect<void, FooError, never>) => Effect.Effect<void, never, never>): Effect.Effect<void, never, never> (+21 overloads)
pipe
(
import Effect
Effect
.
const catchTag: <"FooError", FooError, void, never, never, unassigned, never, never>(k: "FooError", f: (e: FooError) => Effect.Effect<void, never, never>, orElse?: ((e: never) => Effect.Effect<unassigned, never, never>) | undefined) => <A, R>(self: Effect.Effect<A, FooError, R>) => Effect.Effect<void | A, never, R> (+1 overload)

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.

Example (Handling a tagged error)

import { Effect } from "effect"
class NetworkError {
readonly _tag = "NetworkError"
constructor(readonly message: string) {}
}
class ValidationError {
readonly _tag = "ValidationError"
constructor(readonly message: string) {}
}
const task: Effect.Effect<string, NetworkError | ValidationError> =
Effect.fail(new NetworkError("offline"))
const program = Effect.catchTag(
task,
"NetworkError",
(error) => Effect.succeed(`Recovered from network error: ${error.message}`)
)
Effect.runSync(program) // => "Recovered from network error: offline"

@see ― catchTags for handling multiple tagged errors in one call

@see ― catchIf for recovering from errors that match a predicate

@stability ― stable

@category ― error handling

@since ― 2.0.0

catchTag
("FooError", (
e: FooError
e
) =>
import Effect
Effect
.
const log: (...message: ReadonlyArray<any>) => Effect.Effect<void>

Logs one or more messages using the default log level.

Example (Logging at the default level)

import { Effect, Logger } from "effect"
const output: Array<unknown> = []
const program = Effect.gen(function*() {
const result = 2 + 2
yield* Effect.log("Result:", result)
return result
})
const logger = Logger.make<unknown, void>(({ logLevel, message }) => {
void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`)
})
const runnable = Effect.provide(program, Logger.layer([logger]))
void output.push(Effect.runSync(runnable))
output // => ["Info: Result: 4", 4]

@stability ― stable

@category ― logging

@since ― 2.0.0

log
("recovered",
e: FooError
e
.
bar: string
bar
)),
);

The Problem

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:

abstract class
class CategoryA
CategoryA
extends
var Error: ErrorConstructor
Error
{}
abstract class
class CategoryB
CategoryB
extends
var Error: ErrorConstructor
Error
{}
class
class FooError
FooError
extends
class CategoryA
CategoryA
{}
class
class BarError
BarError
extends
class CategoryA
CategoryA
{}
class
class BazError
BazError
extends
class CategoryB
CategoryB
{}
try {
// ...
} catch (
var error: unknown
error
) {
if (
var error: unknown
error
instanceof
class CategoryA
CategoryA
) {
// do A
} else if (
var error: unknown
error
instanceof
class CategoryB
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.

Good thing there is another way…

Mixins (and composition) to the rescuse

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.

type
type Class<T = {}> = new (...args: any[]) => T
Class
<
function (type parameter) T in type Class<T = {}>
T
= {}> = new (...
args: any[]
args
: any[]) =>
function (type parameter) T in type Class<T = {}>
T
;
const
const Mixin: <T extends Class<{
message: string;
}>>(Base: T) => {
new (...args: any[]): (Anonymous class);
prototype: Mixin<any>.(Anonymous class);
} & T
Mixin
= <
function (type parameter) T in <T extends Class<{
message: string;
}>>(Base: T): {
new (...args: any[]): (Anonymous class);
prototype: Mixin<any>.(Anonymous class);
} & T
T
extends
type Class<T = {}> = new (...args: any[]) => T
Class
<{
message: string
message
: string }>>(
type Base: T extends Class<{ message: string; }>
Base
:
function (type parameter) T in <T extends Class<{
message: string;
}>>(Base: T): {
new (...args: any[]): (Anonymous class);
prototype: Mixin<any>.(Anonymous class);
} & T
T
) =>
class extends
type Base: T extends Class<{ message: string; }>
Base
{
get
function (Anonymous class).message2: string
message2
() {
return this.
message: string
message
+ this.
message: string
message
;
}
};
class
class MyError
MyError
extends
const Mixin: <ErrorConstructor>(Base: ErrorConstructor) => {
new (...args: any[]): Mixin<ErrorConstructor>.(Anonymous class);
prototype: Mixin<any>.(Anonymous class);
} & ErrorConstructor
Mixin
(
var Error: ErrorConstructor
Error
) {
MyError.message: string
message
= "hi";
}
const
const e: MyError
e
= new
constructor MyError(message?: string, options?: ErrorOptions): MyError (+1 overload)
MyError
();
var console: Console
console
.
Console.log(...data: any[]): void

The console.log() static method outputs a message to the console.

MDN Reference

log
(
const e: MyError
e
.
function (Anonymous class).message2: string
message2
); // "hihi"

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 {
function pipe<A>(a: A): A (+19 overloads)

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"
const numbers = [1, 2, 3, 4]
const double = (n: number) => n * 2
const greaterThanFour = (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
type Class<T = {}> = new (...args: any[]) => T
Class
<
function (type parameter) T in type Class<T = {}>
T
= {}> = new (...
args: any[]
args
: any[]) =>
function (type parameter) T in type Class<T = {}>
T
;
const
const Mixin1: <T extends Class>(Base: T) => {
new (...args: any[]): (Anonymous class);
prototype: Mixin1<any>.(Anonymous class);
} & T
Mixin1
= <
function (type parameter) T in <T extends Class>(Base: T): {
new (...args: any[]): (Anonymous class);
prototype: Mixin1<any>.(Anonymous class);
} & T
T
extends
type Class<T = {}> = new (...args: any[]) => T
Class
>(
type Base: T extends Class
Base
:
function (type parameter) T in <T extends Class>(Base: T): {
new (...args: any[]): (Anonymous class);
prototype: Mixin1<any>.(Anonymous class);
} & T
T
) =>
class extends
type Base: T extends Class
Base
{
function (Anonymous class).one: boolean
one
= true;
};
const
const Mixin2: <T extends Class>(Base: T) => {
new (...args: any[]): (Anonymous class);
prototype: Mixin2<any>.(Anonymous class);
} & T
Mixin2
= <
function (type parameter) T in <T extends Class>(Base: T): {
new (...args: any[]): (Anonymous class);
prototype: Mixin2<any>.(Anonymous class);
} & T
T
extends
type Class<T = {}> = new (...args: any[]) => T
Class
>(
type Base: T extends Class
Base
:
function (type parameter) T in <T extends Class>(Base: T): {
new (...args: any[]): (Anonymous class);
prototype: Mixin2<any>.(Anonymous class);
} & T
T
) =>
class extends
type Base: T extends Class
Base
{
function (Anonymous class).two: boolean
two
= true;
};
class
class MyError
MyError
extends
pipe<ErrorConstructor, {
new (...args: any[]): Mixin1<ErrorConstructor>.(Anonymous class);
prototype: Mixin1<any>.(Anonymous class);
} & ErrorConstructor, {
new (...args: any[]): Mixin2<{
new (...args: any[]): Mixin1<ErrorConstructor>.(Anonymous class);
prototype: Mixin1<any>.(Anonymous class);
} & ErrorConstructor>.(Anonymous class);
prototype: Mixin2<...>.(Anonymous class);
} & {
new (...args: any[]): Mixin1<ErrorConstructor>.(Anonymous class);
prototype: Mixin1<any>.(Anonymous class);
} & ErrorConstructor>(a: ErrorConstructor, ab: (a: ErrorConstructor) => {
new (...args: any[]): Mixin1<ErrorConstructor>.(Anonymous class);
prototype: Mixin1<any>.(Anonymous class);
} & ErrorConstructor, bc: (b: {
new (...args: any[]): Mixin1<ErrorConstructor>.(Anonymous class);
prototype: Mixin1<any>.(Anonymous class);
} & ErrorConstructor) => {
new (...args: any[]): Mixin2<{
new (...args: any[]): Mixin1<ErrorConstructor>.(Anonymous class);
prototype: Mixin1<any>.(Anonymous class);
} & ErrorConstructor>.(Anonymous class);
prototype: Mixin2<...>.(Anonymous class);
} & ... 1 more ... & ErrorConstructor): {
new (...args: any[]): Mixin2<{
new (...args: any[]): Mixin1<ErrorConstructor>.(Anonymous class);
prototype: Mixin1<any>.(Anonymous class);
} & ErrorConstructor>.(Anonymous class);
prototype: Mixin2<...>.(Anonymous class);
} & ... 1 more ... & ErrorConstructor (+19 overloads)

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"
const numbers = [1, 2, 3, 4]
const double = (n: number) => n * 2
const greaterThanFour = (n: number) => n > 4
pipe(
numbers,
Array.map(double),
Array.filter(greaterThanFour)
) // => [6, 8]

@stability ― stable

@category ― combinators

@since ― 2.0.0

pipe
(
var Error: ErrorConstructor
Error
,
const Mixin1: <T extends Class>(Base: T) => {
new (...args: any[]): (Anonymous class);
prototype: Mixin1<any>.(Anonymous class);
} & T
Mixin1
,
const Mixin2: <T extends Class>(Base: T) => {
new (...args: any[]): (Anonymous class);
prototype: Mixin2<any>.(Anonymous class);
} & T
Mixin2
) {}
const
const e: MyError
e
= new
constructor MyError(message?: string, options?: ErrorOptions): MyError (+1 overload)
MyError
();
var console: Console
console
.
Console.log(...data: any[]): void

The console.log() static method outputs a message to the console.

MDN Reference

log
(
const e: MyError
e
.
function (Anonymous class).one: boolean
one
&&
const e: MyError
e
.
function (Anonymous class).two: boolean
two
); // true

Back to categories

Ok, so mixins are a cool pattern. But how does this help us with our error categorization problem?

Well, we can start by making a unique interface for each category:

const
const CategoryA: typeof CategoryA
CategoryA
=
var Symbol: SymbolConstructor
Symbol
.
SymbolConstructor.for(key: string): symbol

Returns a Symbol object from the global symbol registry matching the given key if found. Otherwise, returns a new symbol with this key.

@param ― key key to search for.

for
("CategoryA");
interface
interface A
A
{
readonly [
const CategoryA: typeof CategoryA
CategoryA
]: true;
}
const
const CategoryB: typeof CategoryB
CategoryB
=
var Symbol: SymbolConstructor
Symbol
.
SymbolConstructor.for(key: string): symbol

Returns a Symbol object from the global symbol registry matching the given key if found. Otherwise, returns a new symbol with this key.

@param ― key key to search for.

for
("CategoryB");
interface
interface B
B
{
readonly [
const CategoryB: typeof CategoryB
CategoryB
]: true;
B.double(): number
double
(): number;
}

Then, we can create a mixin that adds the necessary properties for each interface to the provided class:

const
const AMixin: <T extends Class>(Base: T) => {
new (...args: any[]): (Anonymous class);
prototype: AMixin<any>.(Anonymous class);
} & T
AMixin
= <
function (type parameter) T in <T extends Class>(Base: T): {
new (...args: any[]): (Anonymous class);
prototype: AMixin<any>.(Anonymous class);
} & T
T
extends
type Class<T = {}> = new (...args: any[]) => T
Class
>(
type Base: T extends Class
Base
:
function (type parameter) T in <T extends Class>(Base: T): {
new (...args: any[]): (Anonymous class);
prototype: AMixin<any>.(Anonymous class);
} & T
T
) =>
class extends
type Base: T extends Class
Base
implements
interface A
A
{
readonly [
const CategoryA: typeof CategoryA
CategoryA
] = true as
type const = true
const
;
};
const
const BMixin: <T extends Class<{
x: number;
}>>(Base: T) => {
new (...args: any[]): (Anonymous class);
prototype: BMixin<any>.(Anonymous class);
} & T
BMixin
= <
function (type parameter) T in <T extends Class<{
x: number;
}>>(Base: T): {
new (...args: any[]): (Anonymous class);
prototype: BMixin<any>.(Anonymous class);
} & T
T
extends
type Class<T = {}> = new (...args: any[]) => T
Class
<{
x: number
x
: number }>>(
type Base: T extends Class<{ x: number; }>
Base
:
function (type parameter) T in <T extends Class<{
x: number;
}>>(Base: T): {
new (...args: any[]): (Anonymous class);
prototype: BMixin<any>.(Anonymous class);
} & T
T
) =>
class extends
type Base: T extends Class<{ x: number; }>
Base
implements
interface B
B
{
readonly [
const CategoryB: typeof CategoryB
CategoryB
] = true as
type const = true
const
;
function (Anonymous class).double(): number
double
() {
return 2 * this.
x: number
x
;
}
};

Now we can take our TaggedErrors from before and just pipe them into the category mixins they belong to:

class
class FooError
FooError
extends
import Schema
Schema
.
const TaggedError: <FooError, {}>(identifier?: string) => {
<Tag, Fields>(tag: Tag, fields: Fields, annotations?: Schema.Annotations.Declaration<FooError, readonly [Schema.TaggedStruct<Tag, Fields>]> | undefined): Schema.Class<FooError, Schema.TaggedStruct<Tag, Fields>, YieldableError>;
<Tag, S>(tag: Tag, schema: S, annotations?: Schema.Annotations.Declaration<FooError, readonly [Schema.Struct<{ [K in keyof ({
readonly _tag: Schema.tag<Tag>;
} & S["fields"])]: ({
readonly _tag: Schema.tag<Tag>;
} & S["fields"])[K]; }>]> | undefined): Schema.Class<...>;
}

Defines a schema-backed yieldable error class with an automatically populated _tag field.

When to use

Use to define typed errors that are schema validated, yielded in Effect.gen, and matched as tagged union members.

Example (Defining a tagged error class)

import { Effect, Schema } from "effect"
class NotFound extends Schema.TaggedError<NotFound>()("NotFound", {
id: Schema.Number
}) {}
const program = Effect.gen(function*() {
yield* new NotFound({ id: 42 })
})
const error = await Effect.runPromise(Effect.flip(program))
error._tag // => "NotFound"
error.id // => 42

@stability ― stable

@category ― constructors

@since ― 3.10.0

TaggedError
<
class FooError
FooError
>()("FooError", {}) {}
class
class BarError
BarError
extends
import Schema
Schema
.
const TaggedError: <BarError, {}>(identifier?: string) => {
<Tag, Fields>(tag: Tag, fields: Fields, annotations?: Schema.Annotations.Declaration<BarError, readonly [Schema.TaggedStruct<Tag, Fields>]> | undefined): Schema.Class<BarError, Schema.TaggedStruct<Tag, Fields>, YieldableError>;
<Tag, S>(tag: Tag, schema: S, annotations?: Schema.Annotations.Declaration<BarError, readonly [Schema.Struct<{ [K in keyof ({
readonly _tag: Schema.tag<Tag>;
} & S["fields"])]: ({
readonly _tag: Schema.tag<Tag>;
} & S["fields"])[K]; }>]> | undefined): Schema.Class<...>;
}

Defines a schema-backed yieldable error class with an automatically populated _tag field.

When to use

Use to define typed errors that are schema validated, yielded in Effect.gen, and matched as tagged union members.

Example (Defining a tagged error class)

import { Effect, Schema } from "effect"
class NotFound extends Schema.TaggedError<NotFound>()("NotFound", {
id: Schema.Number
}) {}
const program = Effect.gen(function*() {
yield* new NotFound({ id: 42 })
})
const error = await Effect.runPromise(Effect.flip(program))
error._tag // => "NotFound"
error.id // => 42

@stability ― stable

@category ― constructors

@since ― 3.10.0

TaggedError
<
class BarError
BarError
>()("BarError", {
x: Schema.Number
x
:
import Schema
Schema
.
const Number: Schema.Number

Type-level representation of

Number

.

Schema for number values, including NaN, Infinity, and -Infinity.

Details

Default JSON serializer:

  • Finite numbers are serialized as numbers.
  • Non-finite values are serialized as strings ("NaN", "Infinity", "-Infinity").

@stability ― stable

@category ― models

@since ― 4.0.0

@see ― Finite for a schema that excludes non-finite values.

@stability ― stable

@category ― schemas

@since ― 4.0.0

Number
,
}).
Pipeable.pipe<Schema.Class<BarError, Schema.TaggedStruct<"BarError", {
readonly x: Schema.Number;
}>, YieldableError>, {
new (...args: any[]): AMixin<Schema.Class<BarError, Schema.TaggedStruct<"BarError", {
readonly x: Schema.Number;
}>, YieldableError>>.(Anonymous class);
prototype: AMixin<any>.(Anonymous class);
} & Schema.Class<BarError, Schema.TaggedStruct<"BarError", {
readonly x: Schema.Number;
}>, YieldableError>>(this: Schema.Class<...>, ab: (_: Schema.Class<...>) => {
new (...args: any[]): AMixin<Schema.Class<BarError, Schema.TaggedStruct<"BarError", {
readonly x: Schema.Number;
}>, YieldableError>>.(Anonymous class);
prototype: AMixin<any>.(Anonymous class);
} & Schema.Class<...>): {
new (...args: any[]): AMixin<Schema.Class<BarError, Schema.TaggedStruct<"BarError", {
readonly x: Schema.Number;
}>, YieldableError>>.(Anonymous class);
prototype: AMixin<any>.(Anonymous class);
} & Schema.Class<...> (+21 overloads)
pipe
(
const AMixin: <T extends Class>(Base: T) => {
new (...args: any[]): (Anonymous class);
prototype: AMixin<any>.(Anonymous class);
} & T
AMixin
) {}
class
class BazError
BazError
extends
import Schema
Schema
.
const TaggedError: <BazError, {}>(identifier?: string) => {
<Tag, Fields>(tag: Tag, fields: Fields, annotations?: Schema.Annotations.Declaration<BazError, readonly [Schema.TaggedStruct<Tag, Fields>]> | undefined): Schema.Class<BazError, Schema.TaggedStruct<Tag, Fields>, YieldableError>;
<Tag, S>(tag: Tag, schema: S, annotations?: Schema.Annotations.Declaration<BazError, readonly [Schema.Struct<{ [K in keyof ({
readonly _tag: Schema.tag<Tag>;
} & S["fields"])]: ({
readonly _tag: Schema.tag<Tag>;
} & S["fields"])[K]; }>]> | undefined): Schema.Class<...>;
}

Defines a schema-backed yieldable error class with an automatically populated _tag field.

When to use

Use to define typed errors that are schema validated, yielded in Effect.gen, and matched as tagged union members.

Example (Defining a tagged error class)

import { Effect, Schema } from "effect"
class NotFound extends Schema.TaggedError<NotFound>()("NotFound", {
id: Schema.Number
}) {}
const program = Effect.gen(function*() {
yield* new NotFound({ id: 42 })
})
const error = await Effect.runPromise(Effect.flip(program))
error._tag // => "NotFound"
error.id // => 42

@stability ― stable

@category ― constructors

@since ― 3.10.0

TaggedError
<
class BazError
BazError
>()("BazError", {
x: Schema.Number
x
:
import Schema
Schema
.
const Number: Schema.Number

Type-level representation of

Number

.

Schema for number values, including NaN, Infinity, and -Infinity.

Details

Default JSON serializer:

  • Finite numbers are serialized as numbers.
  • Non-finite values are serialized as strings ("NaN", "Infinity", "-Infinity").

@stability ― stable

@category ― models

@since ― 4.0.0

@see ― Finite for a schema that excludes non-finite values.

@stability ― stable

@category ― schemas

@since ― 4.0.0

Number
,
}).
Pipeable.pipe<Schema.Class<BazError, Schema.TaggedStruct<"BazError", {
readonly x: Schema.Number;
}>, YieldableError>, {
new (...args: any[]): AMixin<Schema.Class<BazError, Schema.TaggedStruct<"BazError", {
readonly x: Schema.Number;
}>, YieldableError>>.(Anonymous class);
prototype: AMixin<any>.(Anonymous class);
} & Schema.Class<BazError, Schema.TaggedStruct<"BazError", {
readonly x: Schema.Number;
}>, YieldableError>, {
...;
} & ... 1 more ... & Schema.Class<...>>(this: Schema.Class<...>, ab: (_: Schema.Class<...>) => {
new (...args: any[]): AMixin<Schema.Class<BazError, Schema.TaggedStruct<"BazError", {
readonly x: Schema.Number;
}>, YieldableError>>.(Anonymous class);
prototype: AMixin<any>.(Anonymous class);
} & Schema.Class<...>, bc: (_: {
new (...args: any[]): AMixin<Schema.Class<BazError, Schema.TaggedStruct<"BazError", {
readonly x: Schema.Number;
}>, YieldableError>>.(Anonymous class);
prototype: AMixin<any>.(Anonymous class);
} & Schema.Class<...>) => {
...;
} & ... 1 more ... & Schema.Class<...>): {
...;
} & ... 1 more ... & Schema.Class<...> (+21 overloads)
pipe
(
const AMixin: <T extends Class>(Base: T) => {
new (...args: any[]): (Anonymous class);
prototype: AMixin<any>.(Anonymous class);
} & T
AMixin
,
const BMixin: <T extends Class<{
x: number;
}>>(Base: T) => {
new (...args: any[]): (Anonymous class);
prototype: BMixin<any>.(Anonymous class);
} & T
BMixin
) {}

Next, we can add some utility functions to make working with these categories just as nice as working with _tags.

First, we add a type guard:

const
const hasCategory: <Category extends symbol>(sym: Category) => <A>(x: A) => x is Extract<A, Record<Category, any>>
hasCategory
=
<
function (type parameter) Category in <Category extends symbol>(sym: Category): <A>(x: A) => x is Extract<A, Record<Category, any>>
Category
extends symbol>(
sym: Category extends symbol
sym
:
function (type parameter) Category in <Category extends symbol>(sym: Category): <A>(x: A) => x is Extract<A, Record<Category, any>>
Category
) =>
<
function (type parameter) A in <A>(x: A): x is Extract<A, Record<Category, any>>
A
,>(
x: A
x
:
function (type parameter) A in <A>(x: A): x is Extract<A, Record<Category, any>>
A
):
x: A
x
is
type Extract<T, U> = T extends U ? T : never

Extract from T those types that are assignable to U

Extract
<
function (type parameter) A in <A>(x: A): x is Extract<A, Record<Category, any>>
A
,
type Record<K extends keyof any, T> = { [P in K]: T; }

Construct a type with a set of properties K of type T

Record
<
function (type parameter) Category in <Category extends symbol>(sym: Category): <A>(x: A) => x is Extract<A, Record<Category, any>>
Category
, any>> => {
return
import Predicate
Predicate
.
const hasProperty: <Category>(self: unknown, property: Category) => self is { [K in Category]: unknown; } (+1 overload)

Checks whether a value has a given property key.

When to use

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"
const hasName = Predicate.hasProperty("name")
const data: 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:

const
const catchCategory: <E, Category extends symbol, 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>
catchCategory
=
<
function (type parameter) E in <E, Category extends symbol, 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 (type parameter) Category in <E, Category extends symbol, 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>
Category
extends symbol,
function (type parameter) B in <E, Category extends symbol, 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
,
function (type parameter) E2 in <E, Category extends symbol, 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>
E2
,
function (type parameter) R2 in <E, Category extends symbol, 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>
R2
>(
category: Category extends symbol
category
:
function (type parameter) Category in <E, Category extends symbol, 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>
Category
,
f: (error: Extract<E, Record<Category, any>>) => Effect.Effect<B, E2, R2>
f
: (
error: Extract<E, Record<Category, any>>
error
:
type Extract<T, U> = T extends U ? T : never

Extract from T those types that are assignable to U

Extract
<
function (type parameter) E in <E, Category extends symbol, 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
,
type Record<K extends keyof any, T> = { [P in K]: T; }

Construct a type with a set of properties K of type T

Record
<
function (type parameter) Category in <E, Category extends symbol, 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>
Category
, any>>,
) =>
import Effect
Effect
.
interface Effect<out A, out E = never, out R = 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 (type parameter) B in <E, Category extends symbol, 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
,
function (type parameter) E2 in <E, Category extends symbol, 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>
E2
,
function (type parameter) R2 in <E, Category extends symbol, 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>
R2
>,
) =>
<
function (type parameter) A in <A, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A | B, Exclude<E, Record<Category, any>> | E2, R | R2>
A
,
function (type parameter) R in <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
.
interface Effect<out A, out E = never, out R = 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 (type parameter) A in <A, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A | B, Exclude<E, Record<Category, any>> | E2, R | R2>
A
,
function (type parameter) E in <E, Category extends symbol, 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 (type parameter) R in <A, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A | B, Exclude<E, Record<Category, any>> | E2, R | R2>
R
>,
):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = 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 (type parameter) A in <A, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A | B, Exclude<E, Record<Category, any>> | E2, R | R2>
A
|
function (type parameter) B in <E, Category extends symbol, 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
,
type Exclude<T, U> = T extends U ? never : T

Exclude from T those types that are assignable to U

Exclude
<
function (type parameter) E in <E, Category extends symbol, 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
,
type Record<K extends keyof any, T> = { [P in K]: T; }

Construct a type with a set of properties K of type T

Record
<
function (type parameter) Category in <E, Category extends symbol, 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>
Category
, any>> |
function (type parameter) E2 in <E, Category extends symbol, 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>
E2
,
function (type parameter) R in <A, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A | B, Exclude<E, Record<Category, any>> | E2, R | R2>
R
|
function (type parameter) R2 in <E, Category extends symbol, 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>
R2
> =>
import Effect
Effect
.
const catchIf: <A, E, R, Extract<NoInfer<E>, Record<Category, any>>, B, E2, R2, unassigned, never, never>(self: Effect.Effect<A, E, R>, refinement: Predicate.Refinement<NoInfer<E>, Extract<NoInfer<E>, Record<Category, any>>>, f: (e: Extract<NoInfer<E>, Record<Category, any>>) => Effect.Effect<B, E2, R2>, orElse?: ((e: Exclude<E, Extract<NoInfer<E>, Record<...>>>) => Effect.Effect<...>) | undefined) => Effect.Effect<...> (+3 overloads)

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.

Example (Recovering when a predicate matches)

import { Data, Effect, Filter } from "effect"
class NotFound extends Data.TaggedError("NotFound")<{ id: string }> {}
const program = Effect.fail(new NotFound({ id: "user-1" }))
// With a refinement
const recovered = program.pipe(
Effect.catchIf(
(error): error is NotFound => error._tag === "NotFound",
(error) => Effect.succeed(`missing:${error.id}`)
)
)
// With a Filter
const recovered2 = program.pipe(
Effect.catchFilter(
Filter.tagged("NotFound"),
(error) => Effect.succeed(`missing:${error.id}`)
)
)
Effect.runSync(Effect.all([recovered, recovered2])) // => ['missing:user-1', 'missing:user-1']

@stability ― stable

@category ― error handling

@since ― 2.0.0

catchIf
(
effect: Effect.Effect<A, E, R>
effect
,
const hasCategory: <Category>(sym: Category) => <A>(x: A) => x is Extract<A, Record<Category, any>>
hasCategory
(
category: Category extends symbol
category
),
f: (error: Extract<E, Record<Category, any>>) => Effect.Effect<B, E2, R2>
f
) as any;
declare const
const example: Effect.Effect<void, FooError | BarError | BazError, never>
example
:
import Effect
Effect
.
interface Effect<out A, out E = never, out R = 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
<void,
class FooError
FooError
|
class BarError
BarError
|
class BazError
BazError
>;
// only FooError left (A's removed)
const test1 =
const example: Effect.Effect<void, FooError | BarError | BazError, never>
example
.
Pipeable.pipe<Effect.Effect<void, FooError | BarError | BazError, never>, Effect.Effect<void, FooError, never>>(this: Effect.Effect<void, FooError | BarError | BazError, never>, ab: (_: Effect.Effect<void, FooError | BarError | BazError, never>) => Effect.Effect<void, FooError, never>): Effect.Effect<void, FooError, never> (+21 overloads)
pipe
(
const test1: Effect.Effect<void, FooError, never>
const catchCategory: <FooError | BarError | BazError, typeof CategoryA, void, never, never>(category: typeof CategoryA, f: (error: BarError | BazError) => Effect.Effect<void, never, never>) => <A, R>(effect: Effect.Effect<A, FooError | BarError | BazError, R>) => Effect.Effect<void | A, FooError, R>
catchCategory
(
const CategoryA: typeof CategoryA
CategoryA
, (
error: BarError | BazError
error
) =>
import Effect
Effect
.
const void: Effect.Effect<void, never, never>
export void

Returns an effect that succeeds with void.

@stability ― stable

@category ― constructors

@since ― 2.0.0

void
),
);
// example of using added behavior
const
const test2: Effect.Effect<void, FooError | BarError, never>
test2
=
const example: Effect.Effect<void, FooError | BarError | BazError, never>
example
.
Pipeable.pipe<Effect.Effect<void, FooError | BarError | BazError, never>, Effect.Effect<void, FooError | BarError, never>>(this: Effect.Effect<void, FooError | BarError | BazError, never>, ab: (_: Effect.Effect<void, FooError | BarError | BazError, never>) => Effect.Effect<void, FooError | BarError, never>): Effect.Effect<void, FooError | BarError, never> (+21 overloads)
pipe
(
const catchCategory: <FooError | BarError | BazError, typeof CategoryB, void, never, never>(category: typeof CategoryB, f: (error: BazError) => Effect.Effect<void, never, never>) => <A, R>(effect: Effect.Effect<A, FooError | BarError | BazError, R>) => Effect.Effect<void | A, FooError | BarError, R>
catchCategory
(
const CategoryB: typeof CategoryB
CategoryB
, (
error: BazError
error
) =>
import Effect
Effect
.
const log: (...message: ReadonlyArray<any>) => Effect.Effect<void>

Logs one or more messages using the default log level.

Example (Logging at the default level)

import { Effect, Logger } from "effect"
const output: Array<unknown> = []
const program = Effect.gen(function*() {
const result = 2 + 2
yield* Effect.log("Result:", result)
return result
})
const logger = Logger.make<unknown, void>(({ logLevel, message }) => {
void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`)
})
const runnable = Effect.provide(program, Logger.layer([logger]))
void output.push(Effect.runSync(runnable))
output // => ["Info: Result: 4", 4]

@stability ― stable

@category ― logging

@since ― 2.0.0

log
(
error: BazError
error
.
function (Anonymous class)<{ new (...args: any[]): AMixin<Class<BazError, TaggedStruct<"BazError", { readonly x: Number; }>, YieldableError>>.(Anonymous class); prototype: AMixin<...>.(Anonymous class); } & Class<...>>.double(): number
double
())),
);

Conclusion

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