Custom Exceptions and Error Strategy

Domain-specific exceptions communicate failure meaning to callers.

public final class InsufficientBalanceException
        extends RuntimeException {
    public InsufficientBalanceException(String message) {
        super(message);
    }
}

At service boundaries, convert low-level failures into domain-level errors when that improves the API contract. Avoid leaking secrets, SQL statements with sensitive values, access tokens, or personal data into exception messages and logs.

Key Takeaways
  • Exceptions are part of an API's behavioral contract.
  • Wrap low-level failures when a higher-level abstraction has more meaning.
  • Keep sensitive information out of exception messages and logs.