Andrey Solera
Andrey Solera

Reputation: 2402

Dart Result with TypeError Exception

I have the following Result object:

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._();
}

I have a function that returns a Future with a Result object like so:

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

I think I'm using Generics in a proper way, however, I get the following error:

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

How can I return an Exception using Result.error?

Upvotes: 0

Views: 365

Answers (1)

spkersten
spkersten

Reputation: 3396

The error subclass should be something like this:

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

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

The type T is for the data, not the type of the exception.

Upvotes: 1

Related Questions