在flutter documentation之后,我在flutter应用中实现了一种用于管理未处理异常的全局策略:
Future<Null> main() async {
// This captures errors reported by the Flutter framework.
FlutterError.onError = (FlutterErrorDetails details) async {
if (isInDebugMode) {
// In development mode simply print to console.
FlutterError.dumpErrorToConsole(details);
} else {
// In production mode report to the application zone to report to
// Sentry.
Zone.current.handleUncaughtError(details.exception, details.stack);
}
};
// This creates a [Zone] that contains the Flutter application and stablishes
// an error handler that captures errors and reports them.
//
// Using a zone makes sure that as many errors as possible are captured,
// including those thrown from [Timer]s, microtasks, I/O, and those forwarded
// from the `FlutterError` handler.
//
// More about zones:
//
// - https://api.dartlang.org/stable/1.24.2/dart-async/Zone-class.html
// - https://www.dartlang.org/articles/libraries/zones
runZoned<Future<Null>>(() async {
runApp(new CrashyApp());
}, onError: (error, stackTrace) async {
await _reportError(error, stackTrace);
});
}
当我使用FutureBuilder小部件并且关联的Future引发异常时,该异常被视为已处理,并且将显示错误文本:
FutureBuilder<Post>(
future: _post,
builder: (BuildContext context, AsyncSnapshot<Post> snapshot) {
return snapshot.connectionState == ConnectionState.done
? snapshot.hasData
? _buildRoot(snapshot.data)
: const Text('error')
: const Text('loading...');
})
我在这里的问题是,异常被视为已处理,并且永远不会在onError
函数中发送到runZoned
回调中。
您对使用futureBuilder
小部件时将来将异常发送到全局异常处理程序有何建议?