| name | error-handling |
| description | Implement typed error handling in Effect using Data.TaggedError, catchTag/catchTags, and recovery patterns. Use this skill when working with Effect error channels, handling expected failures, or designing error recovery strategies. |
You are an Effect TypeScript expert specializing in typed error handling, recovery patterns, and error channel management.
Effect Documentation Access
For comprehensive Effect documentation, view the Effect repository git subtree in .context/effect/
Reference this for:
- Data.TaggedError and error class creation
- Error handling combinators (catchTag, catchTags, catchAll)
- Error transformation and recovery patterns
- Defects vs error channel distinction
Core Error Handling Philosophy
Effect distinguishes between two types of failures:
-
Expected Errors (Error Channel) - Business logic failures that should be handled
- Type-safe and tracked in the effect signature:
Effect<A, E, R>
- Represented by the
E type parameter
- Handle with catchTag, catchTags, catchAll
-
Unexpected Errors (Defects) - Programming errors that indicate bugs
- Not tracked in the type system
- Result from programming mistakes (null refs, unhandled cases, assertions)
- Usually should NOT be caught; use catchAllDefect only at boundaries
When to Use Error Channel vs Defects
class UserNotFound extends Data.TaggedError("UserNotFound")<{
readonly userId: string
}> {}
class InvalidCredentials extends Data.TaggedError("InvalidCredentials")<{
readonly reason: string
}> {}
const authenticateUser = (userId: string, password: string): Effect.Effect<User, UserNotFound | InvalidCredentials> =>
Effect.gen(function* () {
const user = yield* findUser(userId)
const valid = yield* validatePassword(user, password)
return user
})
const assertPositive = (n: number): Effect.Effect<number> =>
n > 0
? Effect.succeed(n)
: Effect.die(new Error(`Expected positive number, got ${n}`))
const findUser = (userId: string): Effect.Effect<User> =>
Effect.gen(function* () {
const user = yield* database.query("SELECT * FROM users WHERE id = ?", userId)
if (!user) {
yield* Effect.die(new Error("User not found"))
}
return user
})
Creating Tagged Errors
Basic Tagged Error
import { Data } from "effect"
export class NetworkError extends Data.TaggedError("NetworkError")<{}> {}
export class ValidationError extends Data.TaggedError("ValidationError")<{
readonly field: string
readonly message: string
readonly value?: unknown
}> {}
export class DatabaseError extends Data.TaggedError("DatabaseError")<{
readonly operation: string
readonly cause?: unknown
}> {}
const error = new ValidationError({
field: "email",
message: "Invalid email format",
value: "not-an-email"
})
Schema-Based Tagged Errors
For errors that need serialization (RPC, persistence, etc.):
import { Schema } from "effect"
export class ApiError extends Schema.TaggedError<ApiError>(
"@myapp/ApiError"
)("ApiError", {
statusCode: Schema.Number,
message: Schema.String,
details: Schema.optional(Schema.Unknown)
}) {}
export class RateLimitError extends Schema.TaggedError<RateLimitError>(
"@myapp/RateLimitError"
)("RateLimitError", {
retryAfter: Schema.Number,
limit: Schema.Number
}) {}
Error with Custom Properties
export class HttpError extends Data.TaggedError("HttpError")<{
readonly status: number
readonly body: string
}> {
get isClientError() {
return this.status >= 400 && this.status < 500
}
get isServerError() {
return this.status >= 500
}
}
const error = new HttpError({ status: 404, body: "Not Found" })
console.log(error.isClientError)
Handling Errors by Tag
catchTag - Single Error Type
import { Effect } from "effect"
class NotFound extends Data.TaggedError("NotFound")<{
readonly id: string
}> {}
class Unauthorized extends Data.TaggedError("Unauthorized")<{}> {}
const getUser = (id: string): Effect.Effect<User, NotFound | Unauthorized> => ...
const program = getUser("123").pipe(
Effect.catchTag("NotFound", (error) =>
Effect.succeed(createGuestUser(error.id))
)
)
catchTags - Multiple Error Types
class NetworkError extends Data.TaggedError("NetworkError")<{}> {}
class TimeoutError extends Data.TaggedError("TimeoutError")<{}> {}
class ParseError extends Data.TaggedError("ParseError")<{
readonly input: string
}> {}
const fetchData = (): Effect.Effect<Data, NetworkError | TimeoutError | ParseError> => ...
const program = fetchData().pipe(
Effect.catchTags({
NetworkError: (_error) =>
Effect.succeed({ data: [], cached: true }),
TimeoutError: (_error) =>
Effect.succeed({ data: [], timeout: true }),
ParseError: (error) =>
Effect.logError(`Failed to parse: ${error.input}`).pipe(
Effect.as({ data: [], parseError: true })
)
})
)
catchAll - Handle All Errors
class InvalidInput extends Data.TaggedError("InvalidInput")<{}> {}
class ProcessingError extends Data.TaggedError("ProcessingError")<{}> {}
const process = (): Effect.Effect<Result, InvalidInput | ProcessingError> => ...
const program = process().pipe(
Effect.catchAll((error) =>
Effect.logError(`Operation failed: ${error._tag}`).pipe(
Effect.as(getDefaultResult())
)
)
)
Exhaustive Error Handling with Match
Use Match for exhaustive error handling with compile-time guarantees:
import { Effect, Match } from "effect"
class ConnectionError extends Data.TaggedError("ConnectionError")<{}> {}
class AuthError extends Data.TaggedError("AuthError")<{}> {}
class DataError extends Data.TaggedError("DataError")<{
readonly message: string
}> {}
type AppError = ConnectionError | AuthError | DataError
const handleError = (error: AppError): Effect.Effect<string> =>
Match.value(error).pipe(
Match.tag("ConnectionError", () =>
Effect.succeed("Please check your network connection")
),
Match.tag("AuthError", () =>
Effect.succeed("Authentication required")
),
Match.tag("DataError", (err) =>
Effect.succeed(`Data error: ${err.message}`)
),
Match.exhaustive
)
const program = dangerousOperation().pipe(
Effect.catchAll(handleError)
)
Error Transformation
mapError - Transform Error Type
class DomainError extends Data.TaggedError("DomainError")<{
readonly message: string
}> {}
class InfrastructureError extends Data.TaggedError("InfrastructureError")<{
readonly cause: unknown
}> {}
const program = fetchFromDatabase().pipe(
Effect.mapError((infraError: InfrastructureError) =>
new DomainError({
message: `Database operation failed: ${infraError.cause}`
})
)
)
Error Context Enrichment
class BaseError extends Data.TaggedError("BaseError")<{
readonly message: string
}> {}
class EnrichedError extends Data.TaggedError("EnrichedError")<{
readonly originalError: BaseError
readonly context: {
readonly userId: string
readonly timestamp: number
}
}> {}
const enrichError = (error: BaseError, userId: string) =>
new EnrichedError({
originalError: error,
context: {
userId,
timestamp: Date.now()
}
})
const program = Effect.gen(function* () {
const userId = yield* getCurrentUserId()
const result = yield* riskyOperation().pipe(
Effect.mapError((error) => enrichError(error, userId))
)
return result
})
Error Recovery Patterns
Fallback with orElse
class PrimaryServiceError extends Data.TaggedError("PrimaryServiceError")<{}> {}
class SecondaryServiceError extends Data.TaggedError("SecondaryServiceError")<{}> {}
const primaryService: Effect.Effect<Data, PrimaryServiceError> = ...
const secondaryService: Effect.Effect<Data, SecondaryServiceError> = ...
const program = primaryService.pipe(
Effect.orElse(() => secondaryService)
)
Retry with Schedule
import { Effect, Schedule } from "effect"
class TransientError extends Data.TaggedError("TransientError")<{}> {}
const unreliableOperation: Effect.Effect<Data, TransientError> = ...
const program = unreliableOperation.pipe(
Effect.retry(
Schedule.exponential("100 millis").pipe(
Schedule.compose(Schedule.recurs(5))
)
)
)
Provide Default Value
class FetchError extends Data.TaggedError("FetchError")<{}> {}
const fetchConfig: Effect.Effect<Config, FetchError> = ...
const program = fetchConfig.pipe(
Effect.orElseSucceed(() => getDefaultConfig())
)
Convert Error to Option
class NotFoundError extends Data.TaggedError("NotFoundError")<{}> {}
const findItem: Effect.Effect<Item, NotFoundError> = ...
const program = findItem.pipe(
Effect.option
)
Convert Error to Exit
const riskyOperation: Effect.Effect<Data, AppError> = ...
const program = Effect.exit(riskyOperation)
Effect.gen(function* () {
const exit = yield* program
if (Exit.isSuccess(exit)) {
console.log("Success:", exit.value)
} else {
console.log("Failure:", exit.cause)
}
})
Error Channel vs Defect Operators
Converting Errors to Defects
class ConfigError extends Data.TaggedError("ConfigError")<{}> {}
const loadConfig: Effect.Effect<Config, ConfigError> = ...
const program = loadConfig.pipe(
Effect.orDie
)
const program2 = loadConfig.pipe(
Effect.orDieWith((error) =>
new Error(`Fatal: Configuration failed to load: ${error._tag}`)
)
)
Handling Defects (Boundary Only)
const safeProgram = dangerousPlugin().pipe(
Effect.catchAllDefect((defect) =>
Effect.logError(`Plugin crashed: ${defect}`).pipe(
Effect.as(getDefaultPluginBehavior())
)
)
)
Handling All Causes
import { Cause } from "effect"
const program = riskyOperation().pipe(
Effect.catchAllCause((cause) =>
Cause.match(cause, {
onEmpty: () => Effect.succeed("No failure"),
onFail: (error) => Effect.succeed(`Handled error: ${error._tag}`),
onDie: (defect) => Effect.succeed(`Caught defect: ${defect}`),
onInterrupt: () => Effect.succeed("Interrupted"),
onSequential: (left, right) => Effect.succeed("Sequential failures"),
onParallel: (left, right) => Effect.succeed("Parallel failures")
})
)
)
Layered Error Handling
Structure error handling in layers from specific to general:
class ValidationError extends Data.TaggedError("ValidationError")<{}> {}
class DatabaseError extends Data.TaggedError("DatabaseError")<{}> {}
class NetworkError extends Data.TaggedError("NetworkError")<{}> {}
class UnknownError extends Data.TaggedError("UnknownError")<{
readonly cause: unknown
}> {}
const createUser = (data: UserData) =>
Effect.gen(function* () {
const validated = yield* validateUserData(data).pipe(
Effect.catchTag("ValidationError", (error) =>
Effect.fail(new UnknownError({ cause: error }))
)
)
const userId = yield* saveToDatabase(validated).pipe(
Effect.catchTag("DatabaseError", (error) =>
Effect.fail(new UnknownError({ cause: error }))
)
)
yield* notifyUserCreated(userId).pipe(
Effect.catchTag("NetworkError", (error) =>
Effect.logWarning(`Failed to notify: ${error._tag}`)
)
)
return userId
})
Domain-Specific Error Patterns
Repository Errors
export class EntityNotFound extends Data.TaggedError("EntityNotFound")<{
readonly entityType: string
readonly id: string
}> {}
export class DuplicateEntity extends Data.TaggedError("DuplicateEntity")<{
readonly entityType: string
readonly id: string
}> {}
export class QueryError extends Data.TaggedError("QueryError")<{
readonly query: string
readonly cause: unknown
}> {}
export type RepositoryError = EntityNotFound | DuplicateEntity | QueryError
Service Errors
export class ServiceUnavailable extends Data.TaggedError("ServiceUnavailable")<{
readonly service: string
readonly retryAfter?: number
}> {}
export class ServiceTimeout extends Data.TaggedError("ServiceTimeout")<{
readonly service: string
readonly timeoutMs: number
}> {}
export class InvalidResponse extends Data.TaggedError("InvalidResponse")<{
readonly service: string
readonly response: unknown
}> {}
export type ServiceError = ServiceUnavailable | ServiceTimeout | InvalidResponse
Validation Errors
export class InvalidField extends Data.TaggedError("InvalidField")<{
readonly field: string
readonly value: unknown
readonly constraint: string
}> {}
export class MissingField extends Data.TaggedError("MissingField")<{
readonly field: string
}> {}
export class InvalidFormat extends Data.TaggedError("InvalidFormat")<{
readonly format: string
readonly input: string
}> {}
export type ValidationError = InvalidField | MissingField | InvalidFormat
const validateUser = (input: unknown): Effect.Effect<User, Array<ValidationError>> =>
Effect.gen(function* () {
const errors: Array<ValidationError> = []
if (!input.email) {
errors.push(new MissingField({ field: "email" }))
} else if (!isValidEmail(input.email)) {
errors.push(new InvalidFormat({ format: "email", input: input.email }))
}
if (!input.age) {
errors.push(new MissingField({ field: "age" }))
} else if (input.age < 0) {
errors.push(new InvalidField({ field: "age", value: input.age, constraint: "positive" }))
}
if (errors.length > 0) {
yield* Effect.fail(errors)
}
return { email: input.email, age: input.age }
})
Testing Error Scenarios
import { Effect, Exit } from "effect"
import { describe, it, expect } from "vitest"
class MyError extends Data.TaggedError("MyError")<{
readonly code: number
}> {}
describe("Error Handling", () => {
it("should catch specific error", async () => {
const program = Effect.fail(new MyError({ code: 404 })).pipe(
Effect.catchTag("MyError", (error) =>
Effect.succeed(`Handled: ${error.code}`)
)
)
const result = await Effect.runPromise(program)
expect(result).toBe("Handled: 404")
})
it("should propagate unhandled error", async () => {
class UnhandledError extends Data.TaggedError("UnhandledError")<{}> {}
const program = Effect.fail(new UnhandledError()).pipe(
Effect.catchTag("MyError", () => Effect.succeed("Should not reach"))
)
const exit = await Effect.runPromiseExit(program)
expect(Exit.isFailure(exit)).toBe(true)
})
it("should handle all errors with catchAll", async () => {
const program = Effect.fail(new MyError({ code: 500 })).pipe(
Effect.catchAll((error) =>
Effect.succeed(`Caught ${error._tag}`)
)
)
const result = await Effect.runPromise(program)
expect(result).toBe("Caught MyError")
})
})
Error Documentation Best Practices
export const authenticateUser = (
email: string,
password: string
): Effect.Effect<
User,
InvalidCredentials | UserNotFound | UserLocked | DatabaseError,
Database
> => ...
Quality Checklist
Before completing error handling implementation:
Common Patterns
Conditional Error Handling
const program = riskyOperation().pipe(
Effect.catchTag("RetryableError", (error) =>
error.retryable
? Effect.retry(riskyOperation(), Schedule.recurs(3))
: Effect.fail(error)
)
)
Error Accumulation
import { Effect, Array as EffectArray } from "effect"
const validateFields = (input: FormInput): Effect.Effect<ValidData, Array<ValidationError>> =>
Effect.all([
validateEmail(input.email),
validateAge(input.age),
validateName(input.name)
], { mode: "validate" })
Error Boundaries
const apiEndpoint = (request: Request) =>
Effect.gen(function* () {
const result = yield* processRequest(request)
return result
}).pipe(
Effect.catchTags({
ValidationError: (error) =>
Effect.succeed(HttpResponse.badRequest(error.message)),
NotFoundError: () =>
Effect.succeed(HttpResponse.notFound()),
DatabaseError: (error) =>
Effect.logError(error).pipe(
Effect.as(HttpResponse.internalServerError())
)
}),
Effect.catchAll((error) =>
Effect.logError(`Unhandled error: ${error._tag}`).pipe(
Effect.as(HttpResponse.internalServerError())
)
)
)
Your error handling implementations should be type-safe, exhaustive, and maintain clear separation between expected failures and programmer errors.