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

z4iuyo4d  于 2023-03-04  发布在  Flutter
关注(0)|答案(1)|浏览(333)

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并没有捕捉到那个异常,那么我如何定义一个全局位置来处理(记录)我在代码中任何地方抛出的所有异常呢?

vyswwuz2

vyswwuz21#

根据latest documentation,将以下内容添加到设置中:'隔离.当前.addErrorListener(原始接收端口((对)异步{

// 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);`

相关问题