Type-Safe Error Handling
Effect provides a type-safe approach to error handling where errors are tracked in the type system. This allows you to handle errors explicitly and ensures you don’t forget to handle failure cases.Defining Custom Errors with Schema.TaggedErrorClass
UseSchema.TaggedErrorClass to define custom errors with a _tag field for discrimination:
Handling Errors with Effect.catchTag
UseEffect.catchTag to handle a specific error by its tag:
Handling Multiple Errors with Effect.catchTags
UseEffect.catchTags to handle several tagged errors in one place with different handlers:
Error Reasons with Effect.catchReason
For errors with nested reason fields, Effect provides specialized handling withEffect.catchReason and Effect.catchReasons:
Defining Errors with Reasons
Handling One Reason
UseEffect.catchReason to handle a specific reason type:
Handling Multiple Reasons
UseEffect.catchReasons to handle multiple reason types:
Unwrapping Reasons into the Error Channel
UseEffect.unwrapReason to move reasons into the error channel for standard error handling:
Best Practices
- Define errors with
Schema.TaggedErrorClassfor type safety and discrimination - Use
Effect.catchTagto handle specific errors by their tag - Use
Effect.catchTagsto handle multiple error types with different handlers - Use
Effect.catchto handle all errors uniformly - For errors with reasons, use
Effect.catchReasonorEffect.catchReasons - Use
Effect.unwrapReasonwhen you want to handle reasons as top-level errors - Always return when raising an error to help TypeScript’s control flow analysis
- Include relevant context in your error classes (IDs, input values, etc.)