Video in progress

How do you handle errors in functional pipelines: stop at the first error or collect all errors and continue? How does this choice affect architecture?

This is a business question: in a payment batch a single error may need to cancel the whole batch (fail-fast), while in an import you need to save the good records and report the bad ones (collecting errors). For the second I model the outcome as a value, a Result type, and split it in two at the end of the pipeline.

📖 Answer

A lambda that throws an exception stops the stream at the first error. Often that is the right behavior, but not everywhere.

Fail-fast fits when:

  • a transactional operation: all or nothing;
  • the error signals a problem in the system (configuration, the DB went down): continuing makes no sense;
  • the input comes from a trusted source and errors aren't expected.

Collecting errors fits when:

  • a CSV/Excel import uploaded by a user: you need the full list, like "the date in row 15 is wrong";
  • sending messages in a batch: one bad number shouldn't stop the others;
  • validation: show all the problems at once.

Java has no standard Result/Either, but with a sealed interface it comes out clean:

sealed interface Result<T> {
    record Ok<T>(T value) implements Result<T> {}
    record Err<T>(int row, String reason) implements Result<T> {}
}

Map<Boolean, List<Result<Customer>>> split = rows.stream()
        .map(parser::parse)                       // returns Result<Customer>, doesn't throw
        .collect(partitioningBy(r -> r instanceof Result.Ok));

List<Customer> good = split.get(true).stream()
        .map(r -> ((Result.Ok<Customer>) r).value()).toList();
List<Result<Customer>> bad = split.get(false);

Effects on architecture:

  • Transaction boundary: if you collect errors, saving the good records is a separate step: you can't wrap the whole import in one transaction. You need commits per chunk and idempotency.
  • Dead letter: where do the failed records go for later processing: a table, a queue, a file.
  • Observability: bad.size() should be a metric. Silently swallowed errors are the worst option.
  • API contract: the client must understand a 207 Multi-Status or an "accepted, report later" response.

I agree on which semantics are needed with the product owner up front. Engineers usually write fail-fast, and then on the first big import comes the complaint that one bad row stopped 100 thousand good ones.