Video in progress
Does returning errors with a Result/Either type instead of exceptions pay off in Java?
For expected business outcomes (validation, "not found", rejected), a sealed Result type gives a clearer contract and makes the compiler force you to handle every case. For infrastructure errors (DB, network), exceptions are better. Turning the whole codebase into Either usually does harm.
📖 Answer
Before Java 21 this was painful: with Either<L, R> libraries (Vavr), the code turned into flatMap chains. Sealed interfaces plus records plus pattern matching made it natural:
sealed interface TransferResult {
record Done(UUID txId) implements TransferResult {}
record InsufficientFunds(Money missing) implements TransferResult {}
record AccountBlocked(String reason) implements TransferResult {}
}
return switch (service.transfer(cmd)) {
case Done d -> ResponseEntity.ok(d.txId());
case InsufficientFunds f -> ResponseEntity.unprocessableEntity().body(f);
case AccountBlocked b -> ResponseEntity.status(403).body(b.reason());
};
What you gain:
- the method signature shows all the outcomes, so no documentation is needed;
- if a new case is added, every caller shows up at compile time;
- no stack trace cost, and it's easy to record the outcomes in metrics.
What you lose:
@Transactionalrollback is tied to unchecked exceptions by default. If you return a Result, you manage rollback yourself (setRollbackOnly, or closing the transaction depending on the outcome);- in a deep call chain, every layer has to check and pass the result along, while exceptions do that for free;
- it's more convenient inside streams/lambdas, but it's a new style for the team.
The boundary I use:
| Situation | Mechanism |
|---|---|
| A business rejection that gets explained to the user | Result |
| A programmer mistake (null, a wrong argument) | an unchecked exception |
| Infrastructure (timeout, DB down) | an exception, with one handler at the top |
| An external API boundary | Result, turned into an HTTP status / error code |
What matters at the staff level is making this decision consistent across teams: write an ADR, have one example module, and hold the line in code review. A mixed style (one service uses Result, its neighbor uses exceptions) is the most expensive option.
Sign up to mark studied questions and save your progress.