0Pricing
Flutter Mobile Development · Lesson

Either, Failure Types, and Functional Error Handling

Model recoverable errors as values using dartz Either and sealed failure types.

Errors as Values

In Clean Architecture, your domain and data layers should not crash the UI with raw exceptions. Instead of throwing across layer boundaries, you model recoverable errors as return values.

The dartz package gives you Either<L, R>: a value that is either a Left (by convention, the failure) or a Right (the success). The caller is forced to handle both.

  • Left = the error path (a Failure)
  • Right = the happy path (your data)

This turns invisible throw/catch control flow into an explicit, type-checked contract.

// A repository method signature in the domain layer
// Future<Either<Failure, User>> getUser(String id);
//
// Left  -> something went wrong (a Failure)
// Right -> the success value (a User)

Modeling Either Ourselves

Before reaching for dartz, it helps to see what Either actually is. It is just a sealed type with two cases. Dart 3 sealed classes make the idea concrete and exhaustive.

The key property: a function returning Either always returns one of two shapes, and the compiler can verify you handled both in a switch.

sealed class Either<L, R> {}

class Left<L, R> extends Either<L, R> {
  final L value;
  Left(this.value);
}

class Right<L, R> extends Either<L, R> {
  final R value;
  Right(this.value);
}

Either<String, int> parsePositive(String s) {
  final n = int.tryParse(s);
  if (n == null) return Left('not a number');
  if (n <= 0) return Left('must be positive');
  return Right(n);
}

void main() {
  final result = parsePositive('42');
  final msg = switch (result) {
    Left(value: final e) => 'Error: $e',
    Right(value: final v) => 'Got $v',
  };
  print(msg);
}

All lessons in this course

  1. Domain, Data, and Presentation Layer Boundaries
  2. Dependency Injection with get_it and injectable
  3. Feature-First Folder Structure and Melos Monorepos
  4. Either, Failure Types, and Functional Error Handling
← Back to Flutter Mobile Development