本片博客的目的是记录异常的捕获与上传效果的实现过程,现分为两个方面阐述。
捕获异常
经过测试,,从捕获程度和效果我把flutter的异常分为三种,分别是Framework异常,Dart异常 和 Engine异常。
Framework异常
可以把它理解为flutter调试时出现的默认的红屏页面,如果在release版本下是一张灰屏。如下面这些情况就会出现这种异常:
class _MyHomePageState extends State<MyHomePage> {
List list;
@override
Widget build(BuildContext context) {
/***************** Framework异常触发 *****************/
list.add('value');
// List<String> numList = ['1', '2'];
// print(numList[5]);
// throw StateError('throw a StateError');
return Scaffold(
appBar: AppBar(
title: Text('FlutterCrashReport'),
),
floatingActionButton: FloatingActionButton(
onPressed: () => _triggerException(),
child: Icon(
Icons.add,
color: Colors.white,
size: 50,
),
),
body: Center(
child: Text('点击+号触发异常'),
),
);
该异常的捕获方式有下面两种:
//只能捕获Framework异常,并自定义Framework错误提示页面(替换掉系统默认红背景的页面)
ErrorWidget.builder = (FlutterErrorDetails flutterErrorDetails) {
print('This is a Framework exception');
return Scaffold(
appBar: AppBar(
title: Text('FlutterCrashReport'),
),
floatingActionButton: FloatingActionButton(
onPressed: () => _triggerException(),
child: Icon(
Icons.add,
color: Colors.white,
size: 50,
),
),
body: SingleChildScrollView(
child: Column(
children: [
Text(flutterErrorDetails.exception.toString()),
Text('----------------------'),
Text(flutterErrorDetails.stack.toString()),
],
),
),
);
};
//Framework/Dart异常都能捕捉到,如空指针,数组越界,throw,
//注:除0异常不会被捕获,也不报错
FlutterError.onError = (FlutterErrorDetails details) async {
print('This is a Framework or Dart exception-(kDebugMode:$kDebugMode)');
if (kDebugMode) {
//debug环境直接控制台输出
FlutterError.dumpErrorToConsole(details);
} else {
//线上环境需要上报
Zone.current.handleUncaughtError(details.exception, details.stack);
}
};
|