首页 > 建站教程 > dart >  dart笔记10:自定义异常正文

dart笔记10:自定义异常

dart笔记10:自定义异常。自定义异常用处不多,但是如果要自己写框架,会有很大用处。Flutter有很多的自定义异常。
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请求异常!';
  }
}