gpt4 book ai didi

exception - Flutter 捕获所有未处理的异常

转载 作者:行者123 更新时间:2023-12-04 06:15:35 25 4
gpt4 key购买 nike

我试图在 Flutter 应用程序中捕获所有未处理的异常,以便将其发送给崩溃报告者。有instructions on how to do this in the Flutter docs .我遵循了这些,并在我的应用程序中添加了两段代码以捕获异常:
通过包装 runApp 来捕获 Dart 错误在 runZoned :

runZoned<Future<void>>(
() async {
runApp(MyApp());
},
onError: (dynamic error, StackTrace stackTrace) {
print("=================== CAUGHT DART ERROR");
// Send report
},
);
通过设置 FlutterError.onError 来捕捉抖动错误:
FlutterError.onError = (FlutterErrorDetails details) {
print("=================== CAUGHT FLUTTER ERROR");
// Send report
};
但是,当我在运行时通过从按钮抛出异常进行测试时:
throw Exception("Just testing");
控制台中出现异常:

════════ Exception Caught By gesture═══════════════════════════════════════════════════════════════The following _Exception was thrown while handling a gesture: Exception:Just testing When the exception wasthrown, this was the stack:

... etc


但是我看不到我的打印语句的迹象(CAUGHT DART ERROR 或 CAUGHT FLUTTER ERROR),并且在这些行上设置断点似乎永远不会命中,所以我认为我的异常处理代码没有捕捉到它。我错过了什么吗?
这是一个最小的可重现示例(单击按钮,该按钮会引发异常,但未按预期捕获):
import 'dart:async';
import 'package:flutter/material.dart';

void main() =>
runZoned<Future<void>>(
() async {
runApp(MyApp());
},
onError: (dynamic error, StackTrace stackTrace) {
print("=================== CAUGHT DART ERROR");
// Send report
// NEVER REACHES HERE - WHY?
},
);

class MyApp extends StatefulWidget {
// This widget is the root of your application.
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

@override
void initState() {
super.initState();

// This captures errors reported by the FLUTTER framework.
FlutterError.onError = (FlutterErrorDetails details) {
print("=================== CAUGHT FLUTTER ERROR");
// Send report
// NEVER REACHES HERE - WHY?
};
}

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: RaisedButton(
child: Text("Throw exception"),
onPressed: () {
throw Exception("This is a test exception");
},
),
),
),
);
}
}

最佳答案

好吧,我想通了是怎么回事。查看了一些相关的 Flutter 问题:

flutter tool is too aggressive about catching exceptions

Make hot mode a little less aggressive about catching errors

Break on "unhandled" exceptions when a debugger is attached

看起来在 Debug模式下,flutter 框架捕获了很多异常,打印到控制台(有时在 UI 本身中以红色和黄色显示),但不会重新抛出 - 所以它们被有效地吞下,并且有您自己的代码无法捕获它们。但是,当您在 Release模式下部署时,这不会发生。因此,我的最小可重现示例在以 Release模式构建时确实会捕获异常。

关于exception - Flutter 捕获所有未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57879455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com