Flutter中如何全局处理自定义抛出的异常?

问题描述 投票:0回答:2

main.dart 中,我使用 2 个回调来处理 flutter 捕获的异常和 flutter 未捕获的异常,如下所示:

void main() async {

  MyErrorsHandler.initialize();
  FlutterError.onError = (details) async {
    FlutterError.presentError(details);
    MyErrorsHandler.onErrorDetails(details);
  };

  PlatformDispatcher.instance.onError = (error, stack){
    MyErrorsHandler.onError(error, stack);
    return true;
  };

  runApp(const ProviderScope(child: MyApp()));
}

但是当我自己抛出异常时,比如发出 HTTP 请求时:

 static Future<BasketViewDto> getAsync(String basketId) async {

    final url = Uri.parse('${ApiConfigurations.BaseUrl}/Baskets/$basketId');

    final response = await http.get(url);

    if (response.statusCode == 200) {
      final result = json.decode(response.body)['result'];

      final BasketViewDto basket = BasketViewDto.fromJson(result);

      return basket;
    } else {
      throw Exception("Failed to get Basket");
    }
  }

OnError 不会捕获该异常。那么我如何定义一个全局位置来处理(记录)我在代码中任何位置抛出的所有异常?

flutter
2个回答
1
投票

根据最新文档,将其添加到您的设置中: `Isolate.current.addErrorListener(RawReceivePort((pair) 异步 {

  // To catch errors that happen outside of the Flutter context, an error listener on the main Isolate is required
  final List<dynamic> errorAndStacktrace = pair;
  await FirebaseCrashlytics.instance.recordError(
    errorAndStacktrace.first,
    errorAndStacktrace.last,
    fatal: true,
  );
}).sendPort);`

0
投票

您可以将代码包装在

runZonedGuarded
中,这将在错误区域中运行代码,这将向您的错误处理程序报告所有未捕获的错误:

void main() async {
  await runZonedGuarded<Future<void>>(
    () async {
      MyErrorsHandler.initialize();
      FlutterError.onError = (details) async {
        FlutterError.presentError(details);
        MyErrorsHandler.onErrorDetails(details);
      };

      PlatformDispatcher.instance.onError = (error, stack) {
        MyErrorsHandler.onError(error, stack);
        return true;
      };

      runApp(const ProviderScope(child: MyApp()));
    },
    (e, s) => MyErrorsHandler.onError(e, s),
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.