You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart中如何借助泛型实现通用异常处理函数?

解决Dart泛型异常处理中无法实例化泛型异常类型的问题

你的核心问题在于Dart的泛型类型参数E只是一个类型标记,不能直接当作构造函数调用。要解决这个问题,你需要让调用者传入一个异常构造器函数,用来将捕获到的错误转换为目标异常类型E。

修改后的泛型异常处理函数

Future<T> exceptionHandler<T, E extends Exception>({
  required ValueGetter<Future<T>> tryBlock,
  required E Function(String error) exceptionCreator, // 新增构造器参数
}) async {
  try {
    return await tryBlock();
  } catch (e) {
    if (e is E) {
      // 如果已经是目标异常类型,直接重抛
      rethrow;
    }
    // 用传入的构造器创建异常并抛出
    throw exceptionCreator(e.toString());
  }
}

使用示例

以你的AuthException和signUp函数为例,调用方式如下:

Future<void> signUp(String email, String password) async {
  await exceptionHandler<void, AuthException>(
    tryBlock: () async {
      // 这里写原本的注册逻辑,比如调用API
      await authApi.register(email, password);
    },
    // 传入AuthException的构造函数,直接用`.new`即可
    exceptionCreator: AuthException.new,
  );
}

扩展说明

如果你的自定义异常构造参数不止error,比如有些异常需要额外的错误码,只需要调整构造器函数的签名即可。比如假设有一个带错误码的异常:

class ApiException implements Exception {
  final String error;
  final int code;

  const ApiException({required this.error, required this.code});
}

调用时就可以传入自定义的构造逻辑:

await exceptionHandler<void, ApiException>(
  tryBlock: () async => apiClient.fetchData(),
  exceptionCreator: (errorMsg) => ApiException(
    error: errorMsg,
    code: 500, // 这里可以根据实际情况传入错误码
  ),
);

内容的提问来源于stack exchange,提问作者Bakri Alkhateeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 07:10:11