Video in progress
How do you design an exception hierarchy for a large project?
One base unchecked exception for domain errors and a few meaningful subtypes: "not found", "rule violated", "access denied". Each is mapped to an HTTP status in one place; technical errors stay separate.
📖 Answer
Both extremes are bad: throwing RuntimeException("xato") for everything, or having 80 exception classes, one per case.
A structure that works:
public abstract sealed class DomainException extends RuntimeException
permits NotFoundException, BusinessRuleException, AccessDeniedException {
private final String code; // a stable code for the frontend and logs
protected DomainException(String code, String message) {
super(message);
this.code = code;
}
public String code() { return code; }
}
public final class BusinessRuleException extends DomainException {
public BusinessRuleException(String code, String message) { super(code, message); }
}
Rules:
- Split types by what the catcher needs. If nobody handles two kinds of errors differently, they can be one type, and the
codefield carries the difference (ORDER_ALREADY_PAID,LIMIT_EXCEEDED). - One translation point. A
@RestControllerAdviceturns domain exceptions intoProblemDetail(built into Spring since version 6; RFC 7807, with a newer revision in RFC 9457). Controllers have no try/catch. - Don't mix technical errors into the domain. Wrap
SQLExceptionorIOExceptionwith acause, but don't turn them into aBusinessRuleException: they should be a 500 and trigger an alert, not a 4xx. - Checked exceptions are usually awkward in the domain layer: they work badly with lambdas and streams. They only make sense where the caller can really recover.
- The cost of
fillInStackTrace: if expected business errors are thrown thousands of times per second, collecting stack traces becomes noticeable. In that case it's better to return a result type (Result).
Sign up to mark studied questions and save your progress.