用途:在 Effect-TS 中实现类型安全的错误处理与校验逻辑。Effect 的 E 通道会跟踪潜在失败,本技能介绍如何定义可区分的自定义错误并按类型处理。
主要能力:用 Data.TaggedError 创建带 _tag 的可区分类型化错误;用 Effect.catchTag 只处理某个特定 tagged 错误;用 Effect.catchAll 处理通道内全部错误;用 Effect.all(..., { mode: 'either' }) 累积多个结果或错误到 Either[]。
用法要点:定义错误时继承 Data.TaggedError,如 export class UserNotFoundError extends Data.TaggedError('UserNotFoundError')<{ userId: string }> {};失败时用 return yield* new UserNotFoundError({ userId: id }) 而非 throw;捕获时 getUser(id).pipe(Effect.catchTag('UserNotFoundError', ...));校验多处字段时用 Effect.all 配合 either 模式,再筛选 Left 收集错误。
适用场景:域逻辑自定义错误类型、按类型精确处理错误、多字段校验并收集全部失败。不适合:非 Effect 代码的普通 try/catch;错误类型无需区分时可直接用 Effect.fail(message)。
限制与常见错误:使用 throw 会破坏错误通道,应改用 Effect.fail 或 yield* new TaggedError();过于宽泛的 catchAll 会吞掉非预期错误,优先用 catchTag;Effect.all 默认在首个错误处短路,需要累积时须显式指定 { mode: 'either' } 或 { mode: 'validate' }。此外官方资料要求具备 effect-ts-fundamentals 的核心概念背景。具体安装命令与版本信息暂未提供。