Video in progress
How do you "translate" exceptions at layer boundaries? Why shouldn't `SQLException` or an HTTP client error leak into the domain?
Each layer should throw errors at its own level of abstraction. If an infrastructure error (SQLException, WebClientResponseException) leaks into the domain, the upper layers become tied to a concrete technology. The adapter catches it and wraps it in a domain-language error, keeping the cause.
📖 Answer
The problem:
// domain service
try {
rate = cbuClient.fetch(code);
} catch (HttpClientErrorException.NotFound e) { // a RestTemplate detail got into the domain
...
}
If tomorrow you move to RestClient or another provider, the domain code has to change too. This breaks DIP through exceptions.
The translation happens in the adapter:
@Component
class CbuRateProvider implements RateProvider {
public Rate fetch(CurrencyCode code) {
try {
return client.get(code);
} catch (HttpClientErrorException.NotFound e) {
throw new UnknownCurrencyException(code); // has domain meaning
} catch (RestClientException e) {
throw new RateProviderUnavailableException(code, e); // technical, cause is kept
}
}
}
The domain now only knows UnknownCurrencyException and RateProviderUnavailableException.
Spring does this for the data layer itself: in beans marked @Repository, SQLException and JPA errors are converted into the DataAccessException hierarchy (DuplicateKeyException, DataIntegrityViolationException...). That's why you never need to catch SQLException in a service.
Two mistakes:
catch (Exception e) { throw new MyException(e.getMessage()); }: thecauseis lost and the stack trace is cut. Alwaysnew X(msg, e);- re-wrapping at every layer: you get 5 levels of "wrapped" errors in the log. Translate only at boundaries.
Sign up to mark studied questions and save your progress.