什么是Either Monad?如何使用它处理错误而不是抛出异常?

解读

国内一线/二线前端面试中,面试官问“Either Monad”通常不是考 FP 黑话,而是想看三件事:

  1. 你是否理解“异常”与“错误值”的本质区别;
  2. 能否用纯函数式套路把“失败路径”显式化,避免 try/catch 地狱;
  3. 是否能在真实业务(Node.js 接口、React 数据流、Serverless 函数)里落地,而不是背概念。

Either 的核心语义是“二选一”:Left 表示异常/失败,Right 表示成功。它把“抛”变成“返回”,把“捕获”变成“链式折叠”,从而让错误传播变成普通值传递,代码路径可组合、可推断、可测试。

知识点

  1. Monad 三定律在 Either 上的体现(Left/Right 都要满足结合律、单位元)。
  2. 与 Promise 的对比:Promise 只能 reject 一次,Either 可以多次链式 map/flatMap,且同步异步都通吃。
  3. 与 TypeScript 结合:利用泛型 Either<L, R> 能在编译期把“可能出错”强制显式化,比 throw 更利于重构。
  4. 常见变体:fp-ts、Monet、Remeda、RxJS 的 iif,以及自研最小实现(百行以内)。
  5. 性能陷阱:频繁链式 Either 会生成大量临时对象,在热路径(百万级循环)里需要结构共享或编译期优化。

答案

  1. 概念
    Either Monad 是一个代数数据类型,只有两个构造子:Left<L> 与 Right<R>。它把“失败”与“成功”都封装成普通值,从而避免抛异常带来的堆栈展开与不可预测的控制流。

  2. 最简实现(TypeScript,无第三方依赖,可直接写进简历“手写代码”栏)

type Either<L, R> = Left<L> | Right<R>;

class Left<L> {
  readonly tag = 'Left';
  constructor(readonly value: L) {}
  isLeft(): this is Left<L> { return true; }
  isRight(): this is Right<R> { return false; }
  map<T>(_fn: (r: R) => T): Either<L, T> { return this as any; }
  flatMap<T>(_fn: (r: R) => Either<L, T>): Either<L, T> { return this as any; }
  fold<T>(leftFn: (l: L) => T, _rightFn: (r: R) => T): T {
    return leftFn(this.value);
  }
}

class Right<R> {
  readonly tag = 'Right';
  constructor(readonly value: R) {}
  isLeft(): this is Left<L> { return false; }
  isRight(): this is Right<R> { return true; }
  map<T>(fn: (r: R) => T): Either<L, T> {
    return new Right(fn(this.value));
  }
  flatMap<T>(fn: (r: R) => Either<L, T>): Either<L, T> {
    return fn(this.value);
  }
  fold<T>(_leftFn: (l: L) => T, rightFn: (r: R) => T): T {
    return rightFn(this.value);
  }
}

const left = <L, R>(l: L): Either<L, R> => new Left(l);
const right = <L, R>(r: R): Either<L, R> => new Right(r);
  1. 业务落地示例:Node.js 接口参数校验 + 数据库写入,全程不抛异常
type BizError = { code: string; msg: string };

function validateBody(body: any): Either<BizError, UserDto> {
  if (!body.name) return left({ code: 'E1001', msg: '姓名必填' });
  if (!body.age || body.age < 0) return left({ code: 'E1002', msg: '年龄非法' });
  return right({ name: body.name, age: Number(body.age) });
}

async function saveUser(user: UserDto): Promise<Either<BizError, number>> {
  try {
    const id = await db.insert(user); // 可能抛唯一键冲突
    return right(id);
  } catch (e: any) {
    return left({ code: 'E2001', msg: '数据库冲突' });
  }
}

// 组合成“纯”服务层
export async function createUser(req: Request, res: Response) {
  const result = validateBody(req.body)
    .flatMap(dto => EitherAsync.fromPromise(() => saveUser(dto))); // EitherAsync 是 fp-ts 的异步扩展,这里可自研

  result.fold(
    err => res.status(400).json({ error: err }),
    id  => res.json({ data: { id } })
  );
}
  1. 与 React 结合
    在 Redux-Toolkit 或 Zustand 里,把异步 Thunk 的返回值定义为 Either<Error, Data>,组件内部用 useSelector 直接拿到 Either,渲染分支由 .fold 决定,省去 loading/error/data 三套布尔状态。

  2. 测试优势
    Either 是纯值,单元测试无需 expect().toThrow,直接断言 expect(result).toEqual(left({ code: 'E1001' })),可快照、可深比较,CI 更稳定。

拓展思考

  1. 为什么国内团队普遍“谈 FP 色变”?
    要么过度设计(满屏 Category 术语),要么性能踩坑(频繁 new)。面试时可补充“我们只在边界层(校验、IO)用 Either,核心计算仍用纯函数,配合 Object.freeze 与结构共享,GC 压力可控”。

  2. Either 与 Promise 的“双重包装”问题
    真实项目里常出现 Promise<Either<L, R>>,此时可用“异步 Monad Transformer”——EitherAsync、TaskEither,或自研 asyncFlatMap,把两层拍平成一层;面试中把实现思路(Promise + then 链拍平)讲清楚,可体现你对 Event Loop 与 Monad Transformer 的双重理解。

  3. 与 Java 异常机制的对比
    Java Checked Exception 也强制调用方处理,但类型耦合在方法签名,导致“污染”调用链;Either 把错误变值,可自由组合、高阶函数传递,更适合前端高并发、高并行的场景。

  4. 渐进迁移策略
    老代码全是 try/catch,可先从最外层 API 封装“异常捕获器”:
    const safeCall = <T>(fn: () => T): Either<Error, T> => { try { return right(fn()); } catch (e) { return left(e); } }
    然后逐步把内部函数替换成返回 Either,实现“绞杀者模式”重构,面试中说出“绞杀者”关键词,能让面试官眼前一亮。

  5. 性能极致优化
    在 WebGL 或 Node.js 原生扩展的热点代码里,可用 Struct-Typed Array + 位标记实现“值类型 Either”,避开 GC;把思路抛出来,表明你不仅懂业务,还懂引擎。