【问题标题】:Dart Result with TypeError Exception带有 TypeError 异常的 Dart 结果
【发布时间】:2021-01-08 12:13:46
【问题描述】:

我有以下Result 对象:

class Result<T> {
  Result._();

  factory Result.success(T t) = ResultSuccess<T>;

  factory Result.error(T exception) = ResultError<T>;
}

class ResultError<T> extends Result<T> {
  final T exception;

  ResultError(this.exception) : super._();
}

class ResultSuccess<T> extends Result<T> {
  final T value;

  ResultSuccess(this.value) : super._();
}

我有一个函数返回一个 Future 和一个 Result 对象,如下所示:

Future<Result<bool>> doSomething() {
    return future
      .then((value) => Result.success(true))
      .catch ((error) => Result.error(Exception()));
  }

我认为我正在以正确的方式使用 Generics,但是,我收到以下错误:

type 'ResultError<DatabaseException>' is not a subtype of type 'FutureOr<Result<bool>>'

如何使用Result.error 返回Exception

【问题讨论】:

  • 您的doSomething 方法没有返回任何内容?
  • 方法和数据的返回类型不同 doSomething 返回具有 Future> 数据类型的数据,但您要返回的异常与方法的数据类型不匹配,因为异常具有 ResultError 数据类型.
  • ResultError&lt;DatabaseException&gt; 派生自 Result&lt;DatabaseException&gt;,而不是 Result&lt;bool&gt;,因此它们是不兼容的类型。另外,我强烈建议不要使用Future.thenFuture.catch 并使用async/await。这将使您的函数返回的内容更加清晰。
  • @jamesdlin 感谢您的建议,但是,如何设置特定的返回类型,以便当我尝试在结果为 ResultSucees 时获取值时,我无需强制转换即可获得正确的结果类型是吗?
  • 将带有错误类型的成功返回类型塞进一个 Result 是个坏主意,IMO。此外,您仍然需要一种机制来判断 Result 是成功值还是失败值,这与强制转换没有太大区别。如果doSomething 只有一种可能的失败类型,那么您可以在成功类型失败类型上参数化Result

标签: flutter dart asynchronous generics future


【解决方案1】:

错误子类应该是这样的:

class ResultError<T> extends Result<T> {
  final Object exception;

  ResultError(this.exception) : super._();
}

T 类型用于数据,而不是异常类型。

【讨论】:

  • 即使您像 Result&lt;bool&gt;.error(Exception(...)) 一样创建它。 (否则无法推断类型。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-20
  • 1970-01-01
  • 1970-01-01
  • 2013-12-16
  • 2020-06-13
  • 1970-01-01
相关资源
最近更新 更多