Video in progress

Do you return expected business errors (for example "insufficient balance") with an exception or with a result type?

Both are used. If the error is an ordinary branch for the caller and it must always handle it, a result type (a sealed Result) is clearer. If the error should stop the flow and be turned into an HTTP response in one place higher up, an unchecked domain exception is more convenient.

📖 Answer

In Spring applications, exceptions are usually chosen:

public void withdraw(Money amount) {
    if (balance.lessThan(amount)) throw new InsufficientFundsException(id, amount);
    balance = balance.minus(amount);
}

@RestControllerAdvice turns it into a 422, and there is no try/catch in the controller. The downside: the method signature doesn't tell you an error is possible.

The result type version:

sealed interface TransferResult {
    record Done(TransferId id) implements TransferResult {}
    record Rejected(String reason) implements TransferResult {}
}

TransferResult r = transfers.execute(cmd);
return switch (r) {
    case TransferResult.Done d     -> ResponseEntity.ok(d.id());
    case TransferResult.Rejected x -> ResponseEntity.unprocessableEntity().body(x.reason());
};

Here the caller can't ignore the rejection case, because the switch has to be exhaustive.

This is how I usually split it:

  • technical errors (the DB went down, a timeout): always an exception;
  • a business rule violation that the caller must surface immediately: a domain exception;
  • when the outcome is one of several equal variants (approved / rejected / sent for review): a Result.

At high frequency (thousands of rejections a second), the cost of an exception's stack trace can be noticeable too, which is one more argument for the result type.