Skip to main content

Overview

TaggedError is a factory function that creates custom error classes with a _tag discriminator property. This enables exhaustive pattern matching, type-safe error unions, and improved error handling with full type inference. Tagged errors integrate seamlessly with Result types and support cause chaining, JSON serialization, and runtime type guards.

Factory Function

Parameters

string
required
The discriminator tag for this error class. Used for pattern matching and type narrowing.

Returns

Returns a function that creates a class constructor. Call it immediately with type parameters to get your error class:

Instance Properties

string
required
The discriminator tag identifying this error type. Used for exhaustive pattern matching.
string
Optional error message. If included in Props, will be passed to Error constructor.
unknown
Optional error cause. If included in Props, will be chained in the stack trace.
string
Error name, set to the tag value.
string | undefined
Stack trace. When cause is an Error, its stack is appended with “Caused by:” prefix.

Static Methods

is()

Type guard for checking error instances.

Global Type Guard

Checks if a value is ANY TaggedError instance:

Class-Specific Type Guard

Each error class has its own is() method:

Instance Methods

toJSON()

Serializes the error to a plain object.
Returns: Object containing all properties including _tag, name, message, cause, and stack.

Basic Usage

Creating Tagged Errors

Creating Instances

With Result Types

Pattern Matching

Exhaustive Matching

Use matchError for type-safe exhaustive pattern matching:

Partial Matching with Fallback

Use matchErrorPartial when you only want to handle specific error types:
The fallback parameter’s type is automatically narrowed to exclude handled error types.

Advanced Features

Error Cause Chaining

Automatically chains causes in stack traces:
Stack trace will include:

No-Props Errors

Create errors without additional properties:

Custom Constructors

Override the constructor for custom initialization logic:

JSON Serialization

Type Guards

Class-Specific Guards

Generic TaggedError Guard

Best Practices

Always include a message property in your error Props for better debugging.
  1. Use descriptive tags: Make tags match the class name for clarity
  2. Type error unions: Create union types for domain-specific errors
  3. Exhaustive matching: Use matchError instead of if/else chains
  4. Include metadata: Add relevant context to error properties

See Also