void main() { try { testMyException(); } catch (e) { print(e.toString()); } } testMyException() { throw MyException('这是一个自定义的异常'); } class MyException implements Exception { final String msg; MyException([this.msg]); @override String toString() => msg ?? 'MyException'; }基于Exception自定义的http请求错误异常
import 'dart:async'; import 'package:http/http.dart' as http; void main() { httpRequest(); } Future httpRequest() async { try { var url = 'http://127.0.0.1/1.php'; http.get(url).then((response) { if (response.statusCode == 200) { return response; } else if (response.statusCode == 404) { throw StatusException(type: StatusType.STATUS_404, msg: '找不到异常'); } else if (response.statusCode == 500) { throw StatusException(type: StatusType.STATUS_500, msg: '服务器内部发生错误'); } else { throw StatusException(type: StatusType.DEFAULT, msg: '请求异常'); } }); } catch (e) { return print('error:::' + e.toString()); } } //枚举错误类型 enum StatusType { DEFAULT, STATUS_404, STATUS_500, } //自定义错误提示 class StatusException implements Exception { StatusType type; String msg; StatusException({this.type = StatusType.DEFAULT, this.msg}); @override String toString() { return msg ?? 'Http请求异常!'; } }
部分素材资源来源网站,本站提供免费下载,如有侵权请联系站长马上删除!