Token导航 LogoToken导航

Agent Skill · 研究检索

error-handling(错误处理)

error-handling 用于记录任务执行中的错误、用户纠正、经验和能力缺口,适合在 Codex、Claude、Cursor、Gemini CLI 中希望让 Agent 持续沉淀问题、修正和最佳实践时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

error-handling 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证为 MIT,暂无第三方扫描结果,按安装量在研究检索类的 73,675 个 Skill 里排第 64,068。

总安装 306周安装 13GitHub Stars 公开资料未说明下载 107核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
MIT

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:error-handling(错误处理)
来源仓库:https://github.com/front-depiction/claude-setup
仓库路径:skills/error-handling
安装命令:
npx skills add front-depiction/claude-setup --skill "error-handling"
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

AgentSkills.tonpx skills
npx skills add front-depiction/claude-setup --skill "error-handling"

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

用于记录任务执行中的错误与修正经验。帮助 Agent 持续优化能力缺口。适合长期学习循环构建。error-handling 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

安装命令:npx skills add front-depiction/claude-setup --skill "error-handling 注意日志存储安全与访问控制。

来源仓库内路径:skills/error-handling

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add front-depiction/claude-setup --skill "error-handling";命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

error-handling 怎么安装?

在终端执行 npx skills add front-depiction/claude-setup --skill "error-handling"。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

error-handling 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

error-handling 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

error-handling 是免费的吗?

来源标注的许可证是 MIT。本站不代收任何费用,也不托管安装包;能否商用、要不要署名,以许可证原文为准。

error-handling 用的人多吗?

公开数据是累计安装 306 次,近一周安装 13 次,下载 107 次。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

error-handling 安全吗?

没有查到第三方扫描结果,安全性无法从公开资料判断,安装前请自行审查源码、依赖和命令行为。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 许可证明确为 MIT,商用和分发边界好判断。

先想清楚的地方

  • 没有第三方扫描结果,安全性只能靠自己读源码判断。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 要求有安全扫描结论才肯安装的团队。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
error-handling

错误处理 · 本页

306—需要联网MIT未收录

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

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:

  1. 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

  1. 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

import { Effect, Data } from "effect"

declare const findUser: (userId: string) => Effect.Effect<User, UserNotFound>
declare const validatePassword: (user: User, password: string) => Effect.Effect<boolean, InvalidCredentials>
declare const database: { query: (sql: string, ...params: ReadonlyArray<unknown>) => Effect.Effect<unknown> }

interface User {
  readonly id: string
  readonly name: string
}

// CORRECT - Expected business failures in error channel
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) // Can fail with UserNotFound
    const valid = yield* validatePassword(user, password) // Can fail with InvalidCredentials
    return user
  })

// CORRECT - Programmer errors as defects (use Effect.die)
const assertPositive = (n: number): Effect.Effect<number> =>
  n > 0
    ? Effect.succeed(n)
    : Effect.die(new Error(`Expected positive number, got ${n}`))

// WRONG - Business failure as defect
const findUserWrong = (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")) // Should be in error channel!
    }
    return user as User
  })

Creating Tagged Errors

Basic Tagged Error

import { Data } from "effect"

// Simple error with no additional data
export class NetworkError extends Data.TaggedError("NetworkError")<{}> {}

// Error with context data
export class ValidationError extends Data.TaggedError("ValidationError")<{
  readonly field: string
  readonly message: string
  readonly value?: unknown
}> {}

// Error with optional cause
export class DatabaseError extends Data.TaggedError("DatabaseError")<{
  readonly operation: string
  readonly cause?: unknown
}> {}

// Usage
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" // Globally unique identifier for serialization
)("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

import { Data } from "effect"

export class HttpError extends Data.TaggedError("HttpError")<{
  readonly status: number
  readonly body: string
}> {
  // Add computed properties
  get isClientError() {
    return this.status >= 400 && this.status < 500
  }

  get isServerError() {
    return this.status >= 500
  }
}

// Usage
const error = new HttpError({ status: 404, body: "Not Found" })
console.log(error.isClientError) // true

Handling Errors by Tag

catchTag - Single Error Type

import { Effect, Data } from "effect"

declare const createGuestUser: (id: string) => User

interface User {
  readonly id: string
  readonly name: string
}

class NotFound extends Data.TaggedError("NotFound")<{
  readonly id: string
}> {}

class Unauthorized extends Data.TaggedError("Unauthorized")<{}> {}

//          Effect<User, NotFound | Unauthorized, Dependencies>
//      ↓
const getUser = (id: string): Effect.Effect<User, NotFound | Unauthorized> => Effect.fail(new NotFound({ id }))

// Handle single error type
//          Effect<User, Unauthorized, Dependencies>
//      ↓
const program = getUser("123").pipe(
  Effect.catchTag("NotFound", (error) =>
    // Return default user when not found
    Effect.succeed(createGuestUser(error.id))
  )
)

catchTags - Multiple Error Types

import { Effect, Data } from "effect"

interface Data {
  readonly data: ReadonlyArray<unknown>
  readonly cached?: boolean
  readonly timeout?: boolean
  readonly parseError?: boolean
}

class NetworkError extends Data.TaggedError("NetworkError")<{}> {}
class TimeoutError extends Data.TaggedError("TimeoutError")<{}> {}
class ParseError extends Data.TaggedError("ParseError")<{
  readonly input: string
}> {}

//          Effect<Data, NetworkError | TimeoutError | ParseError, Dependencies>
//      ↓
const fetchData = (): Effect.Effect<Data, NetworkError | TimeoutError | ParseError> => Effect.fail(new NetworkError())

// Handle multiple error types at once
//          Effect<Data, never, Dependencies>
//      ↓
const program = fetchData().pipe(
  Effect.catchTags({
    NetworkError: (_error) =>
      Effect.succeed({ data: [], cached: true }),

    TimeoutError: (_error) =>
      Effect.succeed({ data: [], timeout: true }),

    ParseError: (error) =>
      // Access error-specific fields
      Effect.logError(`Failed to parse: ${error.input}`).pipe(
        Effect.as({ data: [], parseError: true })
      )
  })
)

catchAll - Handle All Errors

import { Effect, Data } from "effect"

declare const getDefaultResult: () => Result

interface Result {
  readonly value: string
}

class InvalidInput extends Data.TaggedError("InvalidInput")<{}> {}
class ProcessingError extends Data.TaggedError("ProcessingError")<{}> {}

//          Effect<Result, InvalidInput | ProcessingError, Dependencies>
//      ↓
const process = (): Effect.Effect<Result, InvalidInput | ProcessingError> => Effect.fail(new InvalidInput())

// Handle all errors with single handler
//          Effect<Result, never, Dependencies>
//      ↓
const program = process().pipe(
  Effect.catchAll((error) =>
    // error is typed as: InvalidInput | ProcessingError
    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, Data } from "effect"

declare const dangerousOperation: () => Effect.Effect<string, AppError>

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 // Compiler ensures all cases handled
  )

const program = dangerousOperation().pipe(
  Effect.catchAll(handleError)
)

Error Transformation

mapError - Transform Error Type

import { Effect, Data } from "effect"

declare const fetchFromDatabase: () => Effect.Effect<Data, InfrastructureError>

interface Data {
  readonly value: string
}

class DomainError extends Data.TaggedError("DomainError")<{
  readonly message: string
}> {}

class InfrastructureError extends Data.TaggedError("InfrastructureError")<{
  readonly cause: unknown
}> {}

// Transform infrastructure errors to domain errors
//          Effect<Data, DomainError, Dependencies>
//      ↓
const program = fetchFromDatabase().pipe(
  Effect.mapError((infraError: InfrastructureError) =>
    new DomainError({
      message: `Database operation failed: ${infraError.cause}`
    })
  )
)

Error Context Enrichment

import { Effect, Data } from "effect"

declare const getCurrentUserId: () => Effect.Effect<string>
declare const riskyOperation: () => Effect.Effect<string, BaseError>

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

import { Effect, Data } from "effect"

interface Data {
  readonly value: string
}

class PrimaryServiceError extends Data.TaggedError("PrimaryServiceError")<{}> {}
class SecondaryServiceError extends Data.TaggedError("SecondaryServiceError")<{}> {}

const primaryService: Effect.Effect<Data, PrimaryServiceError> = Effect.fail(new PrimaryServiceError())
const secondaryService: Effect.Effect<Data, SecondaryServiceError> = Effect.fail(new SecondaryServiceError())

// Try primary, fallback to secondary
//          Effect<Data, SecondaryServiceError, Dependencies>
//      ↓
const program = primaryService.pipe(
  Effect.orElse(() => secondaryService)
)

Retry with Schedule

import { Effect, Schedule, Data } from "effect"

interface Data {
  readonly value: string
}

class TransientError extends Data.TaggedError("TransientError")<{}> {}

const unreliableOperation: Effect.Effect<Data, TransientError> = Effect.fail(new TransientError())

// Retry with exponential backoff
const program = unreliableOperation.pipe(
  Effect.retry(
    Schedule.exponential("100 millis").pipe(
      Schedule.compose(Schedule.recurs(5)) // Max 5 retries
    )
  )
)

Provide Default Value

import { Effect, Data } from "effect"

declare const getDefaultConfig: () => Config

interface Config {
  readonly port: number
  readonly host: string
}

class FetchError extends Data.TaggedError("FetchError")<{}> {}

const fetchConfig: Effect.Effect<Config, FetchError> = Effect.fail(new FetchError())

// Provide default on failure
//          Effect<Config, never, Dependencies>
//      ↓
const program = fetchConfig.pipe(
  Effect.orElseSucceed(() => getDefaultConfig())
)

Convert Error to Option

import { Effect, Data, Option } from "effect"

interface Item {
  readonly id: string
  readonly name: string
}

class NotFoundError extends Data.TaggedError("NotFoundError")<{}> {}

const findItem: Effect.Effect<Item, NotFoundError> = Effect.fail(new NotFoundError())

// Convert to Option (None if error)
//          Effect<Option<Item>, never, Dependencies>
//      ↓
const program = findItem.pipe(
  Effect.option
)

Convert Error to Exit

import { Effect, Exit, Data } from "effect"

interface Data {
  readonly value: string
}

class AppError extends Data.TaggedError("AppError")<{
  readonly message: string
}> {}

const riskyOperation: Effect.Effect<Data, AppError> = Effect.fail(new AppError({ message: "error" }))

// Get Exit with full cause information
//          Effect<Exit<Data, AppError>, never, Dependencies>
//      ↓
const program = Effect.exit(riskyOperation)

// Handle Exit
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

import { Effect, Data } from "effect"

interface Config {
  readonly port: number
  readonly host: string
}

class ConfigError extends Data.TaggedError("ConfigError")<{}> {}

const loadConfig: Effect.Effect<Config, ConfigError> = Effect.fail(new ConfigError())

// Convert error to defect (terminates fiber)
//          Effect<Config, never, Dependencies>
//      ↓
const program = loadConfig.pipe(
  Effect.orDie // Error becomes a defect
)

// With custom defect message
const program2 = loadConfig.pipe(
  Effect.orDieWith((error) =>
    new Error(`Fatal: Configuration failed to load: ${error._tag}`)
  )
)

Handling Defects (Boundary Only)

import { Effect } from "effect"

declare const dangerousPlugin: () => Effect.Effect<unknown>
declare const getDefaultPluginBehavior: () => unknown

// NOTE: ONLY use at application boundaries
const safeProgram = dangerousPlugin().pipe(
  Effect.catchAllDefect((defect) =>
    Effect.logError(`Plugin crashed: ${defect}`).pipe(
      Effect.as(getDefaultPluginBehavior())
    )
  )
)

Handling All Causes

import { Effect, Cause } from "effect"

declare const riskyOperation: () => Effect.Effect<unknown>

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:

import { Effect, Data } from "effect"

declare const validateUserData: (data: UserData) => Effect.Effect<ValidatedUserData, ValidationError>
declare const saveToDatabase: (data: ValidatedUserData) => Effect.Effect<string, DatabaseError>
declare const notifyUserCreated: (userId: string) => Effect.Effect<void, NetworkError>

interface UserData {
  readonly name: string
  readonly email: string
}

interface ValidatedUserData {
  readonly name: string
  readonly email: string
}

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* () {
    // Layer 1: Validate input
    const validated = yield* validateUserData(data).pipe(
      Effect.catchTag("ValidationError", (error) =>
        Effect.fail(new UnknownError({ cause: error }))
      )
    )

    // Layer 2: Database operation
    const userId = yield* saveToDatabase(validated).pipe(
      Effect.catchTag("DatabaseError", (error) =>
        Effect.fail(new UnknownError({ cause: error }))
      )
    )

    // Layer 3: Network notification
    yield* notifyUserCreated(userId).pipe(
      Effect.catchTag("NetworkError", (error) =>
        // Non-critical: log but don't fail
        Effect.logWarning(`Failed to notify: ${error._tag}`)
      )
    )

    return userId
  })

Domain-Specific Error Patterns

Repository Errors

import { Data } from "effect"

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

import { Data } from "effect"

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

import { Effect, Data } from "effect"

declare const isValidEmail: (email: string) => boolean

interface User {
  readonly email: string
  readonly age: number
}

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

// Collect multiple validation errors
const validateUser = (input: any): 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, Data } 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

import { Effect, Data } from "effect"

declare const NotFound: typeof Data.TaggedError

interface User {
  readonly id: string
  readonly name: string
}

interface Database {}

class InvalidCredentials extends Data.TaggedError("InvalidCredentials")<{}> {}
class UserNotFound extends Data.TaggedError("UserNotFound")<{}> {}
class UserLocked extends Data.TaggedError("UserLocked")<{
  readonly unlockAt: Date
}> {}
class DatabaseError extends Data.TaggedError("DatabaseError")<{}> {}

/**
 * Authenticates a user with the provided credentials.
 *
 * @param email - User email address
 * @param password - User password
 * @returns Effect that succeeds with User or fails with auth errors
 *
 * @category Authentication
 * @since 1.0.0
 *
 * @errors
 * - `InvalidCredentials` - Email or password is incorrect
 * - `UserNotFound` - No user exists with the given email
 * - `UserLocked` - Account is temporarily locked due to failed attempts
 * - `DatabaseError` - Database query failed
 */
export const authenticateUser = (
  email: string,
  password: string
): Effect.Effect<
  User,
  InvalidCredentials | UserNotFound | UserLocked | DatabaseError,
  Database
> => Effect.fail(new UserNotFound())

Quality Checklist

Before completing error handling implementation:

  • [ ] All domain errors use Data.TaggedError or Schema.TaggedError
  • [ ] Error types have meaningful, specific names
  • [ ] Errors include relevant context (ids, values, reasons)
  • [ ] Business failures in error channel, programmer errors as defects
  • [ ] catchTag/catchTags used for specific error handling
  • [ ] catchAll only when handling truly all error types
  • [ ] Error transformations preserve important context
  • [ ] Recovery strategies match business requirements
  • [ ] Defect handling only at application boundaries
  • [ ] Error types exported from domain modules
  • [ ] JSDoc includes @errors section listing possible failures
  • [ ] Tests cover error scenarios
  • [ ] Type signatures accurately reflect error channel

Common Patterns

Conditional Error Handling

import { Effect, Schedule, Data } from "effect"

declare const riskyOperation: () => Effect.Effect<unknown, RetryableError>

class RetryableError extends Data.TaggedError("RetryableError")<{
  readonly retryable: boolean
}> {}

const program = riskyOperation().pipe(
  Effect.catchTag("RetryableError", (error) =>
    error.retryable
      ? Effect.retry(riskyOperation(), Schedule.recurs(3))
      : Effect.fail(error)
  )
)

Error Accumulation

import { Effect } from "effect"

declare const validateEmail: (email: string) => Effect.Effect<string, ValidationError>
declare const validateAge: (age: number) => Effect.Effect<number, ValidationError>
declare const validateName: (name: string) => Effect.Effect<string, ValidationError>

interface FormInput {
  readonly email: string
  readonly age: number
  readonly name: string
}

interface ValidData {
  readonly email: string
  readonly age: number
  readonly name: string
}

interface ValidationError {
  readonly _tag: string
}

const validateFields = (input: FormInput): Effect.Effect<ValidData, Array<ValidationError>> =>
  Effect.all([
    validateEmail(input.email),
    validateAge(input.age),
    validateName(input.name)
  ], { mode: "validate" }).pipe(
    Effect.map(([email, age, name]) => ({ email, age, name }))
  ) as Effect.Effect<ValidData, Array<ValidationError>>

Error Boundaries

import { Effect, Data } from "effect"

declare const processRequest: (request: Request) => Effect.Effect<Response, ValidationError | NotFoundError | DatabaseError>
declare const HttpResponse: {
  badRequest: (message: string) => Response
  notFound: () => Response
  internalServerError: () => Response
}

interface Request {
  readonly url: string
}

interface Response {
  readonly status: number
}

class ValidationError extends Data.TaggedError("ValidationError")<{
  readonly message: string
}> {}

class NotFoundError extends Data.TaggedError("NotFoundError")<{}> {}

class DatabaseError extends Data.TaggedError("DatabaseError")<{}> {}

// Define clear boundaries where errors are handled
const apiEndpoint = (request: Request) =>
  Effect.gen(function* () {
    // Business logic
    const result = yield* processRequest(request)
    return result
  }).pipe(
    // Error boundary: convert all errors to HTTP responses
    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())
        )
    }),
    // Catch any unhandled errors
    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.

平台分布

Claude Code

31.16%
按下载量换算33

windsurf

22.78%
按下载量换算24

trae

20.31%
按下载量换算22

OpenCode

12.92%
按下载量换算14

Codex

7.57%
按下载量换算8

Antigravity

3.86%
按下载量换算4

安全审计

暂无安全审计结果可展示。

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills