effect-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Effect-TS Best Practices

Effect-TS 最佳实践

This skill enforces opinionated, consistent patterns for Effect-TS codebases. These patterns optimize for type safety, testability, observability, and maintainability.
此 skill 为 Effect-TS 代码库强制实施一套主观但一致的模式。这些模式旨在优化类型安全性、可测试性、可观测性和可维护性。

Quick Reference: Critical Rules

快速参考:关键规则

CategoryDODON'T
Services
Effect.Service
with
accessors: true
Context.Tag
for business logic
Dependencies
dependencies: [Dep.Default]
in service
Manual
Layer.provide
at usage sites
Errors
Schema.TaggedError
with
message
field
Plain classes or generic Error
Error Specificity
UserNotFoundError
,
SessionExpiredError
Generic
NotFoundError
,
BadRequestError
Error Handling
catchTag
/
catchTags
catchAll
or
mapError
IDs
Schema.UUID.pipe(Schema.brand("@App/EntityId"))
Plain
string
for entity IDs
Functions
Effect.fn("Service.method")
Anonymous generators
Logging
Effect.log
with structured data
console.log
Config
Config.*
with validation
process.env
directly
Options
Option.match
with both cases
Option.getOrThrow
Nullability
Option<T>
in domain types
null
/
undefined
Atoms
Atom.make
outside components
Creating atoms inside render
Atom State
Atom.keepAlive
for global state
Forgetting keepAlive for persistent state
Atom Updates
useAtomSet
in React components
Atom.update
imperatively from React
Atom Cleanup
get.addFinalizer()
for side effects
Missing cleanup for event listeners
Atom Results
Result.builder
with
onErrorTag
Ignoring loading/error states
分类应做不应做
服务使用带
accessors: true
的
Effect.Service
对业务逻辑使用
Context.Tag
依赖项在服务中使用
dependencies: [Dep.Default]
在调用位置手动使用
Layer.provide
错误使用带
message
字段的
Schema.TaggedError
普通类或泛型
Error
错误具体性
UserNotFoundError
、
SessionExpiredError
泛化的
NotFoundError
、
BadRequestError
错误处理
catchTag
/
catchTags
catchAll
或
mapError
ID
Schema.UUID.pipe(Schema.brand("@App/EntityId"))
实体 ID 使用普通
string
函数
Effect.fn("Service.method")
匿名 generator
日志使用带结构化数据的
Effect.log
console.log
配置使用带验证的
Config.*
直接使用
process.env
选项使用
Option.match
并处理两种情况
Option.getOrThrow
可空性领域类型中使用
Option<T>
null
/
undefined
Atom在组件外调用
Atom.make
在渲染过程中创建 Atom
Atom 状态全局状态使用
Atom.keepAlive
持久化状态遗漏
keepAlive
Atom 更新在 React 组件中使用
useAtomSet
在 React 中命令式调用
Atom.update
Atom 清理副作用使用
get.addFinalizer()
事件监听器未清理
Atom 结果使用带
onErrorTag
的
Result.builder
忽略加载/错误状态

Service Definition Pattern

服务定义模式

Always use
Effect.Service
for business logic services. This provides automatic accessors, built-in
Default
layer, and proper dependency declaration.
typescript
import { Effect } from "effect";

export class UserService extends Effect.Service<UserService>()("UserService", {
  accessors: true,
  dependencies: [UserRepo.Default, CacheService.Default],
  effect: Effect.gen(function* () {
    const repo = yield* UserRepo;
    const cache = yield* CacheService;

    const findById = Effect.fn("UserService.findById")(function* (id: UserId) {
      const cached = yield* cache.get(id);
      if (Option.isSome(cached)) return cached.value;

      const user = yield* repo.findById(id);
      yield* cache.set(id, user);
      return user;
    });

    const create = Effect.fn("UserService.create")(function* (data: CreateUserInput) {
      const user = yield* repo.create(data);
      yield* Effect.log("User created", { userId: user.id });
      return user;
    });

    return { findById, create };
  }),
}) {}

// Usage - dependencies are already wired
const program = Effect.gen(function* () {
  const user = yield* UserService.findById(userId);
  return user;
});

// At app root
const MainLive = Layer.mergeAll(UserService.Default, OtherService.Default);
When
Context.Tag
is acceptable:
  • Infrastructure with runtime injection (Cloudflare KV, worker bindings)
  • Factory patterns where resources are provided externally
See
references/service-patterns.md
for detailed patterns.
业务逻辑服务始终使用
Effect.Service
。
这会自动生成 accessor、内置
Default
layer,并正确声明依赖项。
typescript
import { Effect } from "effect";

export class UserService extends Effect.Service<UserService>()("UserService", {
  accessors: true,
  dependencies: [UserRepo.Default, CacheService.Default],
  effect: Effect.gen(function* () {
    const repo = yield* UserRepo;
    const cache = yield* CacheService;

    const findById = Effect.fn("UserService.findById")(function* (id: UserId) {
      const cached = yield* cache.get(id);
      if (Option.isSome(cached)) return cached.value;

      const user = yield* repo.findById(id);
      yield* cache.set(id, user);
      return user;
    });

    const create = Effect.fn("UserService.create")(function* (data: CreateUserInput) {
      const user = yield* repo.create(data);
      yield* Effect.log("User created", { userId: user.id });
      return user;
    });

    return { findById, create };
  }),
}) {}

// Usage - dependencies are already wired
const program = Effect.gen(function* () {
  const user = yield* UserService.findById(userId);
  return user;
});

// At app root
const MainLive = Layer.mergeAll(UserService.Default, OtherService.Default);
可使用
Context.Tag
的场景:
  • 支持运行时注入的基础设施(Cloudflare KV、worker bindings)
  • 资源由外部提供的工厂模式
参见
references/service-patterns.md
了解详细模式。

Error Definition Pattern

错误定义模式

Always use
Schema.TaggedError
for errors. This makes them serializable (required for RPC) and provides consistent structure.
typescript
import { Schema } from "effect";
import { HttpApiSchema } from "@effect/platform";

export class UserNotFoundError extends Schema.TaggedError<UserNotFoundError>()(
  "UserNotFoundError",
  {
    userId: UserId,
    message: Schema.String,
  },
  HttpApiSchema.annotations({ status: 404 }),
) {}

export class UserCreateError extends Schema.TaggedError<UserCreateError>()(
  "UserCreateError",
  {
    message: Schema.String,
    cause: Schema.optional(Schema.String),
  },
  HttpApiSchema.annotations({ status: 400 }),
) {}
Error handling - use
catchTag
/
catchTags
:
typescript
// CORRECT - preserves type information
yield *
  repo.findById(id).pipe(
    Effect.catchTag("DatabaseError", (err) =>
      Effect.fail(new UserNotFoundError({ userId: id, message: "Lookup failed" })),
    ),
    Effect.catchTag("ConnectionError", (err) =>
      Effect.fail(new ServiceUnavailableError({ message: "Database unreachable" })),
    ),
  );

// CORRECT - multiple tags at once
yield *
  effect.pipe(
    Effect.catchTags({
      DatabaseError: (err) =>
        Effect.fail(new UserNotFoundError({ userId: id, message: err.message })),
      ValidationError: (err) =>
        Effect.fail(new InvalidEmailError({ email: input.email, message: err.message })),
    }),
  );
错误始终使用
Schema.TaggedError
。
这样可确保错误可序列化(RPC 所必需),并提供一致的结构。
typescript
import { Schema } from "effect";
import { HttpApiSchema } from "@effect/platform";

export class UserNotFoundError extends Schema.TaggedError<UserNotFoundError>()(
  "UserNotFoundError",
  {
    userId: UserId,
    message: Schema.String,
  },
  HttpApiSchema.annotations({ status: 404 }),
) {}

export class UserCreateError extends Schema.TaggedError<UserCreateError>()(
  "UserCreateError",
  {
    message: Schema.String,
    cause: Schema.optional(Schema.String),
  },
  HttpApiSchema.annotations({ status: 400 }),
) {}
错误处理——使用
catchTag
/
catchTags
:
typescript
// CORRECT - preserves type information
yield *
  repo.findById(id).pipe(
    Effect.catchTag("DatabaseError", (err) =>
      Effect.fail(new UserNotFoundError({ userId: id, message: "Lookup failed" })),
    ),
    Effect.catchTag("ConnectionError", (err) =>
      Effect.fail(new ServiceUnavailableError({ message: "Database unreachable" })),
    ),
  );

// CORRECT - multiple tags at once
yield *
  effect.pipe(
    Effect.catchTags({
      DatabaseError: (err) =>
        Effect.fail(new UserNotFoundError({ userId: id, message: err.message })),
      ValidationError: (err) =>
        Effect.fail(new InvalidEmailError({ email: input.email, message: err.message })),
    }),
  );

Prefer Explicit Over Generic Errors

优先使用明确错误而非泛化错误

Every distinct failure reason deserves its own error type. Don't collapse multiple failure modes into generic HTTP errors.
typescript
// WRONG - Generic errors lose information
export class NotFoundError extends Schema.TaggedError<NotFoundError>()(
  "NotFoundError",
  { message: Schema.String },
  HttpApiSchema.annotations({ status: 404 }),
) {}

// Then mapping everything to it:
Effect.catchTags({
  UserNotFoundError: (err) => Effect.fail(new NotFoundError({ message: "Not found" })),
  ChannelNotFoundError: (err) => Effect.fail(new NotFoundError({ message: "Not found" })),
  MessageNotFoundError: (err) => Effect.fail(new NotFoundError({ message: "Not found" })),
});
// Frontend gets useless: { _tag: "NotFoundError", message: "Not found" }
// Which resource? User? Channel? Message? Can't tell!
typescript
// CORRECT - Explicit domain errors with rich context
export class UserNotFoundError extends Schema.TaggedError<UserNotFoundError>()(
  "UserNotFoundError",
  { userId: UserId, message: Schema.String },
  HttpApiSchema.annotations({ status: 404 }),
) {}

export class ChannelNotFoundError extends Schema.TaggedError<ChannelNotFoundError>()(
  "ChannelNotFoundError",
  { channelId: ChannelId, message: Schema.String },
  HttpApiSchema.annotations({ status: 404 }),
) {}

export class SessionExpiredError extends Schema.TaggedError<SessionExpiredError>()(
  "SessionExpiredError",
  {
    sessionId: SessionId,
    expiredAt: Schema.DateTimeUtc,
    message: Schema.String,
  },
  HttpApiSchema.annotations({ status: 401 }),
) {}

// Frontend can now show specific UI:
// - UserNotFoundError → "User doesn't exist"
// - ChannelNotFoundError → "Channel was deleted"
// - SessionExpiredError → "Your session expired. Please log in again."
See
references/error-patterns.md
for error remapping and retry patterns.
每一种不同的失败原因都应有独立的错误类型。 不要将多种失败模式归并为泛化的 HTTP 错误。
typescript
// WRONG - Generic errors lose information
export class NotFoundError extends Schema.TaggedError<NotFoundError>()(
  "NotFoundError",
  { message: Schema.String },
  HttpApiSchema.annotations({ status: 404 }),
) {}

// Then mapping everything to it:
Effect.catchTags({
  UserNotFoundError: (err) => Effect.fail(new NotFoundError({ message: "Not found" })),
  ChannelNotFoundError: (err) => Effect.fail(new NotFoundError({ message: "Not found" })),
  MessageNotFoundError: (err) => Effect.fail(new NotFoundError({ message: "Not found" })),
});
// Frontend gets useless: { _tag: "NotFoundError", message: "Not found" }
// Which resource? User? Channel? Message? Can't tell!
typescript
// CORRECT - Explicit domain errors with rich context
export class UserNotFoundError extends Schema.TaggedError<UserNotFoundError>()(
  "UserNotFoundError",
  { userId: UserId, message: Schema.String },
  HttpApiSchema.annotations({ status: 404 }),
) {}

export class ChannelNotFoundError extends Schema.TaggedError<ChannelNotFoundError>()(
  "ChannelNotFoundError",
  { channelId: ChannelId, message: Schema.String },
  HttpApiSchema.annotations({ status: 404 }),
) {}

export class SessionExpiredError extends Schema.TaggedError<SessionExpiredError>()(
  "SessionExpiredError",
  {
    sessionId: SessionId,
    expiredAt: Schema.DateTimeUtc,
    message: Schema.String,
  },
  HttpApiSchema.annotations({ status: 401 }),
) {}

// Frontend can now show specific UI:
// - UserNotFoundError → "User doesn't exist"
// - ChannelNotFoundError → "Channel was deleted"
// - SessionExpiredError → "Your session expired. Please log in again."
参见
references/error-patterns.md
了解错误重映射和重试模式。

Schema & Branded Types Pattern

Schema 与品牌类型模式

Brand all entity IDs for type safety across service boundaries:
typescript
import { Schema } from "effect";

// Entity IDs - always branded
export const UserId = Schema.UUID.pipe(Schema.brand("@App/UserId"));
export type UserId = Schema.Schema.Type<typeof UserId>;

export const OrganizationId = Schema.UUID.pipe(Schema.brand("@App/OrganizationId"));
export type OrganizationId = Schema.Schema.Type<typeof OrganizationId>;

// Domain types - use Schema.Struct
export const User = Schema.Struct({
  id: UserId,
  email: Schema.String,
  name: Schema.String,
  organizationId: OrganizationId,
  createdAt: Schema.DateTimeUtc,
});
export type User = Schema.Schema.Type<typeof User>;

// Input types for mutations
export const CreateUserInput = Schema.Struct({
  email: Schema.String.pipe(Schema.pattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)),
  name: Schema.String.pipe(Schema.minLength(1)),
  organizationId: OrganizationId,
});
export type CreateUserInput = Schema.Schema.Type<typeof CreateUserInput>;
When NOT to brand:
  • Simple strings that don't cross service boundaries (URLs, file paths)
  • Primitive config values
See
references/schema-patterns.md
for transforms and advanced patterns.
为所有实体 ID 添加 brand,以确保跨服务边界的类型安全:
typescript
import { Schema } from "effect";

// Entity IDs - always branded
export const UserId = Schema.UUID.pipe(Schema.brand("@App/UserId"));
export type UserId = Schema.Schema.Type<typeof UserId>;

export const OrganizationId = Schema.UUID.pipe(Schema.brand("@App/OrganizationId"));
export type OrganizationId = Schema.Schema.Type<typeof OrganizationId>;

// Domain types - use Schema.Struct
export const User = Schema.Struct({
  id: UserId,
  email: Schema.String,
  name: Schema.String,
  organizationId: OrganizationId,
  createdAt: Schema.DateTimeUtc,
});
export type User = Schema.Schema.Type<typeof User>;

// Input types for mutations
export const CreateUserInput = Schema.Struct({
  email: Schema.String.pipe(Schema.pattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)),
  name: Schema.String.pipe(Schema.minLength(1)),
  organizationId: OrganizationId,
});
export type CreateUserInput = Schema.Schema.Type<typeof CreateUserInput>;
无需 brand 的情况:
  • 不跨越服务边界的简单字符串(URL、文件路径)
  • 原始配置值
参见
references/schema-patterns.md
了解转换和高级模式。

Function Pattern with Effect.fn

使用 Effect.fn 的函数模式

Always use
Effect.fn
for service methods. This provides automatic tracing with proper span names:
typescript
// CORRECT - Effect.fn with descriptive name
const findById = Effect.fn("UserService.findById")(function* (id: UserId) {
  yield* Effect.annotateCurrentSpan("userId", id);
  const user = yield* repo.findById(id);
  return user;
});

// CORRECT - Effect.fn with multiple parameters
const transfer = Effect.fn("AccountService.transfer")(function* (
  fromId: AccountId,
  toId: AccountId,
  amount: number,
) {
  yield* Effect.annotateCurrentSpan("fromId", fromId);
  yield* Effect.annotateCurrentSpan("toId", toId);
  yield* Effect.annotateCurrentSpan("amount", amount);
  // ...
});
服务方法始终使用
Effect.fn
。
这会自动生成追踪信息,并使用正确的 span 名称:
typescript
// CORRECT - Effect.fn with descriptive name
const findById = Effect.fn("UserService.findById")(function* (id: UserId) {
  yield* Effect.annotateCurrentSpan("userId", id);
  const user = yield* repo.findById(id);
  return user;
});

// CORRECT - Effect.fn with multiple parameters
const transfer = Effect.fn("AccountService.transfer")(function* (
  fromId: AccountId,
  toId: AccountId,
  amount: number,
) {
  yield* Effect.annotateCurrentSpan("fromId", fromId);
  yield* Effect.annotateCurrentSpan("toId", toId);
  yield* Effect.annotateCurrentSpan("amount", amount);
  // ...
});

Layer Composition

Layer 组合

Declare dependencies in the service, not at usage sites:
typescript
// CORRECT - dependencies in service definition
export class OrderService extends Effect.Service<OrderService>()("OrderService", {
  accessors: true,
  dependencies: [UserService.Default, ProductService.Default, PaymentService.Default],
  effect: Effect.gen(function* () {
    const users = yield* UserService;
    const products = yield* ProductService;
    const payments = yield* PaymentService;
    // ...
  }),
}) {}

// At app root - simple merge
const AppLive = Layer.mergeAll(
  OrderService.Default,
  // Infrastructure layers (intentionally not in dependencies)
  DatabaseLive,
  RedisLive,
);
See
references/layer-patterns.md
for testing layers and config-dependent layers.
在服务中声明依赖项,而不是在调用位置声明:
typescript
// CORRECT - dependencies in service definition
export class OrderService extends Effect.Service<OrderService>()("OrderService", {
  accessors: true,
  dependencies: [UserService.Default, ProductService.Default, PaymentService.Default],
  effect: Effect.gen(function* () {
    const users = yield* UserService;
    const products = yield* ProductService;
    const payments = yield* PaymentService;
    // ...
  }),
}) {}

// At app root - simple merge
const AppLive = Layer.mergeAll(
  OrderService.Default,
  // Infrastructure layers (intentionally not in dependencies)
  DatabaseLive,
  RedisLive,
);
参见
references/layer-patterns.md
了解测试 layer 和依赖配置的 layer。

Option Handling

Option 处理

Never use
Option.getOrThrow
. Always handle both cases explicitly:
typescript
// CORRECT - explicit handling
yield *
  Option.match(maybeUser, {
    onNone: () => Effect.fail(new UserNotFoundError({ userId, message: "Not found" })),
    onSome: (user) => Effect.succeed(user),
  });

// CORRECT - with getOrElse for defaults
const name = Option.getOrElse(maybeName, () => "Anonymous");

// CORRECT - Option.map for transformations
const upperName = Option.map(maybeName, (n) => n.toUpperCase());
绝不要使用
Option.getOrThrow
。始终明确处理两种情况:
typescript
// CORRECT - explicit handling
yield *
  Option.match(maybeUser, {
    onNone: () => Effect.fail(new UserNotFoundError({ userId, message: "Not found" })),
    onSome: (user) => Effect.succeed(user),
  });

// CORRECT - with getOrElse for defaults
const name = Option.getOrElse(maybeName, () => "Anonymous");

// CORRECT - Option.map for transformations
const upperName = Option.map(maybeName, (n) => n.toUpperCase());

Effect Atom (Frontend State)

Effect Atom(前端状态)

Effect Atom provides reactive state management for React with Effect integration.
Effect Atom 为 React 提供与 Effect 集成的响应式状态管理。

Basic Atoms

基础 Atom

typescript
import { Atom } from "@effect-atom/atom-react";

// Define atoms OUTSIDE components
const countAtom = Atom.make(0);

// Use keepAlive for global state that should persist
const userPrefsAtom = Atom.make({ theme: "dark" }).pipe(Atom.keepAlive);

// Atom families for per-entity state
const modalAtomFamily = Atom.family((type: string) =>
  Atom.make({ isOpen: false }).pipe(Atom.keepAlive),
);
typescript
import { Atom } from "@effect-atom/atom-react";

// Define atoms OUTSIDE components
const countAtom = Atom.make(0);

// Use keepAlive for global state that should persist
const userPrefsAtom = Atom.make({ theme: "dark" }).pipe(Atom.keepAlive);

// Atom families for per-entity state
const modalAtomFamily = Atom.family((type: string) =>
  Atom.make({ isOpen: false }).pipe(Atom.keepAlive),
);

React Integration

React 集成

typescript
import { useAtomValue, useAtomSet, useAtom, useAtomMount } from "@effect-atom/atom-react"

function Counter() {
    const count = useAtomValue(countAtom)           // Read only
    const setCount = useAtomSet(countAtom)          // Write only
    const [value, setValue] = useAtom(countAtom)    // Read + write

    return <button onClick={() => setCount((c) => c + 1)}>{count}</button>
}

// Mount side-effect atoms without reading value
function App() {
    useAtomMount(keyboardShortcutsAtom)
    return <>{children}</>
}
typescript
import { useAtomValue, useAtomSet, useAtom, useAtomMount } from "@effect-atom/atom-react"

function Counter() {
    const count = useAtomValue(countAtom)           // Read only
    const setCount = useAtomSet(countAtom)          // Write only
    const [value, setValue] = useAtom(countAtom)    // Read + write

    return <button onClick={() => setCount((c) => c + 1)}>{count}</button>
}

// Mount side-effect atoms without reading value
function App() {
    useAtomMount(keyboardShortcutsAtom)
    return <>{children}</>
}

Handling Results with Result.builder

使用 Result.builder 处理结果

Use
Result.builder
for rendering effectful atom results. It provides chainable error handling with
onErrorTag
:
typescript
import { Result } from "@effect-atom/atom-react"

function UserProfile() {
    const userResult = useAtomValue(userAtom) // Result<User, Error>

    return Result.builder(userResult)
        .onInitial(() => <div>Loading...</div>)
        .onErrorTag("NotFoundError", () => <div>User not found</div>)
        .onError((error) => <div>Error: {error.message}</div>)
        .onSuccess((user) => <div>Hello, {user.name}</div>)
        .render()
}
使用
Result.builder
渲染包含 effect 的 Atom 结果。它通过
onErrorTag
提供可链式调用的错误处理:
typescript
import { Result } from "@effect-atom/atom-react"

function UserProfile() {
    const userResult = useAtomValue(userAtom) // Result<User, Error>

    return Result.builder(userResult)
        .onInitial(() => <div>Loading...</div>)
        .onErrorTag("NotFoundError", () => <div>User not found</div>)
        .onError((error) => <div>Error: {error.message}</div>)
        .onSuccess((user) => <div>Hello, {user.name}</div>)
        .render()
}

Atoms with Side Effects

带副作用的 Atom

typescript
const scrollYAtom = Atom.make((get) => {
  const onScroll = () => get.setSelf(window.scrollY);

  window.addEventListener("scroll", onScroll);
  get.addFinalizer(() => window.removeEventListener("scroll", onScroll)); // REQUIRED

  return window.scrollY;
}).pipe(Atom.keepAlive);
See
references/effect-atom-patterns.md
for complete patterns including families, localStorage, and anti-patterns.
typescript
const scrollYAtom = Atom.make((get) => {
  const onScroll = () => get.setSelf(window.scrollY);

  window.addEventListener("scroll", onScroll);
  get.addFinalizer(() => window.removeEventListener("scroll", onScroll)); // REQUIRED

  return window.scrollY;
}).pipe(Atom.keepAlive);
参见
references/effect-atom-patterns.md
了解包括 family、localStorage 和反模式在内的完整模式。

RPC & Cluster Patterns

RPC 与集群模式

For RPC contracts and cluster workflows, see:
  • references/rpc-cluster-patterns.md
    - RpcGroup, Workflow.make, Activity patterns
有关 RPC 合约和集群工作流,请参阅:
  • references/rpc-cluster-patterns.md
    ——RpcGroup、Workflow.make、Activity 模式

Anti-Patterns (Forbidden)

反模式(禁止使用)

These patterns are never acceptable:
typescript
// FORBIDDEN - runSync/runPromise inside services
const result = Effect.runSync(someEffect); // Never do this

// FORBIDDEN - throw inside Effect.gen
yield *
  Effect.gen(function* () {
    if (bad) throw new Error("No!"); // Use Effect.fail instead
  });

// FORBIDDEN - catchAll losing type info
yield * effect.pipe(Effect.catchAll(() => Effect.fail(new GenericError())));

// FORBIDDEN - console.log
console.log("debug"); // Use Effect.log

// FORBIDDEN - process.env directly
const key = process.env.API_KEY; // Use Config.string("API_KEY")

// FORBIDDEN - null/undefined in domain types
type User = { name: string | null }; // Use Option<string>
See
references/anti-patterns.md
for the complete list with rationale.
以下模式绝不可接受:
typescript
// FORBIDDEN - runSync/runPromise inside services
const result = Effect.runSync(someEffect); // Never do this

// FORBIDDEN - throw inside Effect.gen
yield *
  Effect.gen(function* () {
    if (bad) throw new Error("No!"); // Use Effect.fail instead
  });

// FORBIDDEN - catchAll losing type info
yield * effect.pipe(Effect.catchAll(() => Effect.fail(new GenericError())));

// FORBIDDEN - console.log
console.log("debug"); // Use Effect.log

// FORBIDDEN - process.env directly
const key = process.env.API_KEY; // Use Config.string("API_KEY")

// FORBIDDEN - null/undefined in domain types
type User = { name: string | null }; // Use Option<string>
参见
references/anti-patterns.md
了解完整清单及其原因。

Observability

可观测性

typescript
// Structured logging
yield * Effect.log("Processing order", { orderId, userId, amount });

// Metrics
const orderCounter = Metric.counter("orders_processed");
yield * Metric.increment(orderCounter);

// Config with validation
const config = Config.all({
  port: Config.integer("PORT").pipe(Config.withDefault(3000)),
  apiKey: Config.secret("API_KEY"),
  maxRetries: Config.integer("MAX_RETRIES").pipe(
    Config.validate({ message: "Must be positive", validation: (n) => n > 0 }),
  ),
});
See
references/observability-patterns.md
for metrics and tracing patterns.
typescript
// Structured logging
yield * Effect.log("Processing order", { orderId, userId, amount });

// Metrics
const orderCounter = Metric.counter("orders_processed");
yield * Metric.increment(orderCounter);

// Config with validation
const config = Config.all({
  port: Config.integer("PORT").pipe(Config.withDefault(3000)),
  apiKey: Config.secret("API_KEY"),
  maxRetries: Config.integer("MAX_RETRIES").pipe(
    Config.validate({ message: "Must be positive", validation: (n) => n > 0 }),
  ),
});
参见
references/observability-patterns.md
了解指标和追踪模式。

Reference Files

参考文件

For detailed patterns, consult these reference files in the
references/
directory:
  • service-patterns.md
    - Service definition, Effect.fn, Context.Tag exceptions
  • error-patterns.md
    - Schema.TaggedError, error remapping, retry patterns
  • schema-patterns.md
    - Branded types, transforms, Schema.Class
  • layer-patterns.md
    - Dependency composition, testing layers
  • rpc-cluster-patterns.md
    - RpcGroup, Workflow, Activity patterns
  • effect-atom-patterns.md
    - Atom, families, React hooks, Result handling
  • anti-patterns.md
    - Complete list of forbidden patterns
  • observability-patterns.md
    - Logging, metrics, config patterns
有关详细模式,请查阅
references/
目录中的以下参考文件:
  • service-patterns.md
    ——服务定义、Effect.fn、Context.Tag 例外情况
  • error-patterns.md
    ——Schema.TaggedError、错误重映射、重试模式
  • schema-patterns.md
    ——品牌类型、转换、Schema.Class
  • layer-patterns.md
    ——依赖项组合、测试 layer
  • rpc-cluster-patterns.md
    ——RpcGroup、Workflow、Activity 模式
  • effect-atom-patterns.md
    ——Atom、family、React hooks、Result 处理
  • anti-patterns.md
    ——完整的禁止模式清单
  • observability-patterns.md
    ——日志、指标、配置模式