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
Class-Specific Type Guard
Each error class has its ownis() method:
Instance Methods
toJSON()
Serializes the error to a plain object._tag, name, message, cause, and stack.
Basic Usage
Creating Tagged Errors
Creating Instances
With Result Types
Pattern Matching
Exhaustive Matching
UsematchError for type-safe exhaustive pattern matching:
Partial Matching with Fallback
UsematchErrorPartial 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: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
-
Use descriptive tags: Make tags match the class name for clarity
-
Type error unions: Create union types for domain-specific errors
-
Exhaustive matching: Use
matchErrorinstead of if/else chains -
Include metadata: Add relevant context to error properties
See Also
- UnhandledException - Wrapper for caught exceptions
- Panic - Unrecoverable errors
- Result - Error handling with Result types
- matchError - Pattern matching functions