【问题标题】:How can I check subtype of exception in switch case in dart? [duplicate]如何在 dart 的 switch case 中检查异常的子类型? [复制]
【发布时间】:2019-07-23 09:29:15
【问题描述】:

我是 dart 编程的新手,所以我尝试检查嵌套在 FutureBuilder 中的 switch case 中的异常子类型,但我找不到令人满意的解决方案...

我试图检查 switch-case 但它不起作用但是当我尝试使用 is 的 if-else 时它正在工作......

我的自定义异常子类型:

class HttpException implements Exception {
  HttpStatusError status;
  String message;
  HttpException(int statusCode) {
    switch (statusCode) {
      case 400:
        this.status = HttpStatusError.BadRequest;
        this.message = "Bad request";
        break;
      case 401:
        this.status = HttpStatusError.UnAuthorized;
        this.message = "UnAuthorized access ";
        break;
      case 403:
        this.status = HttpStatusError.Forbidden;
        this.message = "Resource access forbidden";
        break;
      case 404:
        this.status = HttpStatusError.NotFound;
        this.message = "Resource not Found";
        break;
      case 500:
        this.status = HttpStatusError.InternalServerError;
        this.message = "Internal server error";
        break;
      default:
        this.status = HttpStatusError.Unknown;
        this.message = "Unknown";
        break;
    }
  }
enum HttpStatusError {
  UnAuthorized,
  BadRequest,
  Forbidden,
  NotFound,
  InternalServerError,
  Unknown
}
if (snapshot.hasError) {
  final error = snapshot.error;
  print(error is HttpException);
  switch (error) {
    case HttpException:
      return Text("http exception";
    case SocketException:
      return Center(child: Text("socket exception"));
   }
   return Center(child: Text("Error occured ${snapshot.error}"));
}

打印指令:print(error is HttpException); 显示true 值,但我没有在SocketException 的情况下输入。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    根据 Dart 语言规范,这是不可能的。

    Dart 中的 Switch 语句使用 == 比较整数、字符串或编译时常量。被比较的对象必须都是同一个类的实例(而不是它的任何子类型),并且该类不能覆盖 ==。枚举类型在 switch 语句中运行良好。

    在您的自定义异常中,您在 switch case 块中使用整数,这是一种有效的数据类型。但是在底部代码中,您试图切换每种类型,这是不受支持的。 也许您可以尝试将这些类转换为字符串,但这会增加更多复杂性。

    https://dart.dev/guides/language/language-tour#switch-and-case

    另一种方法是使用pythonic 方式来实现switch case。 这使用地图/字典,其中键是大小写,值是您要返回的内容,可能是您示例中的提供者。

    Replacements for switch statement in Python?

    【讨论】:

    • 感谢您的回答,但我尝试使用 snapshot.error.runtimeType 并且它正在使用 switch-case。 ?
    • 很高兴知道!谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-10-11
    • 2012-06-16
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    相关资源
    最近更新 更多