我想在Flutter应用程序中捕获所有未处理的异常,以便将其发送到崩溃报告器。 Flutter文档中有关于如何实现此功能的说明。我按照这些说明,向我的应用程序添加了两个代码段来捕获异常:
通过在runApp
中包装runZoned
来捕获Dart错误:
runZoned<Future<void>>(
() async {
runApp(MyApp());
},
onError: (dynamic error, StackTrace stackTrace) {
print("=================== CAUGHT DART ERROR");
// Send report
},
);
通过设置FlutterError.onError
来捕获Flutter错误:
FlutterError.onError = (FlutterErrorDetails details) {
print("=================== CAUGHT FLUTTER ERROR");
// Send report
};
然而,当我在运行时通过从按钮中抛出异常来测试它时:
throw Exception("Just testing");
控制台中出现以下异常:
════════ Exception Caught By gesture ═══════════════════════════════════════════════════════════════ 在处理手势时抛出了以下异常:Exception: Just testing When the exception was thrown, this was the stack:
... 等等
但我看不到我的打印语句(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");
},
),
),
),
);
}
}