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

Flutter开发:如何避免重复编写try-catch异常处理代码?

Dart 重复Try-Catch代码优化方案

方案1:抽离异常处理逻辑为通用函数

把重复的异常判断、日志输出逻辑封装成单独函数,每次catch后调用即可:

void handleException(Object e) {
  if (e is TimeoutException) {
    log('Timeout Error: $e');
  } else if (e is SocketException) {
    log('Socket Error: $e');
  } else if (e is Error) {
    log('General Error: $e');
  } else {
    log('All other Errors: $e');
  }
  rethrow;
}

简化后的try-catch使用:

try {
  // 此处编写你的业务代码
} catch (e) {
  handleException(e);
}

方案2:封装高阶函数包裹业务逻辑

如果想彻底省去编写try-catch的步骤,可以把整个异常处理逻辑封装成高阶函数,直接传入业务代码执行:

import 'dart:async';
import 'dart:io';
import 'package:logger/logger.dart';

final log = Logger();

Future<T> runWithExceptionHandler<T>(Future<T> Function() task) async {
  try {
    return await task();
  } on TimeoutException catch (e) {
    log('Timeout Error: $e');
    rethrow;
  } on SocketException catch (e) {
    log('Socket Error: $e');
    rethrow;
  } on Error catch (e) {
    log('General Error: $e');
    rethrow;
  } catch (e) {
    log('All other Errors: $e');
    rethrow;
  }
}

使用示例:

// 调用高阶函数执行异步业务逻辑
await runWithExceptionHandler(() async {
  // 你的异步业务代码,比如网络请求等
});

两种方案都能有效避免重复编写相同的异常处理代码,方案2更适合大量异步业务场景,进一步减少冗余代码。

内容的提问来源于stack exchange,提问作者Anmol Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:50:24