实现一个可携带堆栈信息的自定义异常类

解读

国内一线/二线互联网公司(阿里、腾讯、字节、美团、小红书、B 站等)在 Flutter 或 Dart 后端面试中,高频出现“如何自定义异常并保留完整堆栈”这一题。
面试官真正想考察的并不是“写个类继承 Exception 就行”,而是:

  1. 你是否知道 Dart 的 StackTrace 是惰性抓取的,必须在 throw 发生的同步帧里捕获;
  2. 你是否能区分 Error/Exception 语义,并正确实现 toString、==、hashCode;
  3. 你是否能在异步、Zone、Isolate 等场景下保证堆栈不丢失;
  4. 你是否熟悉 Dart 2.18+ 的“链式堆栈”机制(Error.throwWithStackTrace),以及 Flutter 官方对“不丢失异步堆栈”的最佳实践;
  5. 你是否能给出单元测试用例,证明异常被 catch 后仍能打印出与原始 throw 点一致的堆栈。

一句话:写出“能带到生产环境”的异常类,而不是 Demo 级玩具。

知识点

  • Dart 的 Exception vs Error 语义差异
  • StackTrace.current 与 StackTrace.fromString 的适用场景
  • throw/throwWithStackTrace 的区别与兼容性
  • 异步链式堆栈(await for、Future.then、Zone 链)
  • 自定义异常实现 ==/hashCode/toString 的规范
  • 异常序列化(toJson/fromJson)在日志/埋点中的价值
  • 单元测试 expect(() => ..., throwsA(isA<YourException>)) 的写法
  • Flutter 官方文档中“Catch errors without losing stack traces”最佳实践

答案

/// 可携带完整堆栈的业务异常
/// 支持同步、异步、Zone、Isolate 场景
class BizException implements Exception {
  final String code;
  final String message;
  final StackTrace? stackTrace;

  const BizException(this.code, this.message, [this.stackTrace]);

  /// 工厂:同步抛异常时立即捕获堆栈
  factory BizException.throwSync(String code, String message) {
    final stack = StackTrace.current;
    throw BizException(code, message, stack);
  }

  /// 工厂:异步场景下使用 Dart 2.18+ 的链式堆栈能力
  static Future<T> throwAsync<T>(String code, String message) async {
    final error = BizException(code, message);
    // 把堆栈绑定到 error 上,await 链不会丢
    return Future.error(error, StackTrace.current);
  }

  /// 支持在 Zone 中捕获后重新抛出,不丢失原始堆栈
  BizException rethrowWithOrigin() {
    Error.throwWithStackTrace(this, stackTrace ?? StackTrace.current);
  }

  @override
  String toString() => 'BizException($code, $message)\n$stackTrace';

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is BizException &&
          runtimeType == other.runtimeType &&
          code == other.code &&
          message == other.message;

  @override
  int get hashCode => Object.hash(code, message);

  /// 日志/埋点友好
  Map<String, dynamic> toJson() => {
        'type': 'BizException',
        'code': code,
        'message': message,
        'stackTrace': stackTrace.toString(),
      };
}

/// 使用示例
void main() async {
  // 1. 同步场景
  try {
    BizException.throwSync('USER_BANNED', '账号被封禁');
  } catch (e, s) {
    print('同步捕获:\n$e\n$s');
  }

  // 2. 异步场景
  await Future(() async {
    await BizException.throwAsync('NETWORK_504', '网关超时');
  }).catchError((e, s) {
    print('异步捕获:\n$e\n$s');
  });

  // 3. Zone 中重新抛
  runZonedGuarded(() {
    final e = BizException('PARAM_ERR', '参数错误');
    e.rethrowWithOrigin();
  }, (e, s) {
    print('Zone 捕获:\n$e\n$s');
  });
}

单元测试(package:test)

test('保留堆栈', () {
  expect(
    () => BizException.throwSync('TEST', 'test'),
    throwsA(
      isA<BizException>()
          .having((e) => e.code, 'code', 'TEST')
          .having((e) => e.stackTrace, 'stackTrace', isNotNull),
    ),
  );
});

拓展思考

  1. 在大型 Flutter 工程中,异常通常需要统一上报到 Sentry、Firebase Crashlytics 或自研日志平台。
    此时 BizException.toJson() 可以直接塞到自定义 key 里,方便后端按 code 聚合告警。

  2. 如果业务需要“可恢复”的异常,可以给 BizException 增加 bool get isRecoverable 字段,并在 UI 层统一弹 Toast/Dialog。

  3. 对于 Dart 服务端(如 dart_frog、alfred),中间件可以 catch BizException 并直接返回 200 带业务 code,避免 500 误告警。

  4. 在 Isolate 场景下,堆栈无法跨 Isolate 传递,解决方案是把 stackTrace.toString() 序列化后随异常一起 send,主 Isolate 收到后再重新 throw 并调用 Error.throwWithStackTrace(..., StackTrace.fromString(...)),实现“伪链式”。

  5. 面试加分项:提到 Dart 3 的 Records 和 Pattern,可以演示如何用 switch 解构 BizException(:var code, :var message),让异常处理代码更函数式。