[toc]
详解Exception异常处理
好文分享:
一、异常的捕获
同步异常通过 try-catch 机制捕获
1 2 3 4 5 6 7 8
| xxx() { try { throw StateError('This is a Dart exception.'); } catch (e) { print(e); } }
|
异步异常采用 Future 提供的 catchError 语句捕获。
1 2 3 4 5 6 7 8 9 10 11 12 13
| Future<Map<String, dynamic>> simulate_get(String url) async { Future.delayed(Duration(seconds: 1)).then((value) { throw StateError('This is a Dart exception in Future.'); return { 'statusCode': 200, 'msg': '"${url}执行成功"', }; }).catchError((onError) { print(onError); }); }
|
二、异常的上抛
异步异常的上抛
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| Future<dynamic> requestBaidu1() async { var url = "https://www.baidu.com/"; try { dynamic response = await simulate_get(url);
if (response['statusCode'] == 200) { return response.data; } else { throw Exception('后端接口出现异常'); } } catch (e) { print('网络错误:======>url:$url \nbody:${e.toString()}'); rethrow; } }
Future<dynamic> requestBaidu2() async { var url = "https://www.baidu.com/"; try { Dio dio = new Dio(); Response response = await dio.get(url);
if (response.statusCode == 200) { return response.data; } else { throw Exception('后端接口出现异常'); } } catch (e) { print('网络错误:======>url:$url \nbody:${e.toString()}'); rethrow; } }
|
进行如上的上抛操作后,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| getData() { Api.requestBaidu2().then((dynamic data) { if (data.isSuccess) { Toast.show("请求成功,有数据 isSuccess = true", context); updateWidgetType(WidgetType.SuccessWithData); } else { Toast.show("服务器失败 isSuccess = false", context); } }).catchError((onError) { print('网络问题'); Toast.show("catchError网络问题111", context); updateWidgetType(WidgetType.ErrorNetwork); }); }
|
判断网络异常
1 2 3 4 5 6 7
| checkNetwork() async { try { final result = await InternetAddress.lookup('baidu.com'); } on SocketException catch (_) { Toast.show("catchError网络问题222333", context); } }
|