Java and Spring Level 2 This level · 53 of 84
Medium java spring

How does Spring Boot handle exception translation?

The 30 second answer

I'd distinguish data-access translation from web exception handling. In data access, Spring turns database-specific exceptions into its unchecked DataAccessException hierarchy. Spring Boot configures PersistenceExceptionTranslationPostProcessor to apply supported translation to @Repository beans through proxies. In the web layer, Spring MVC uses HandlerExceptionResolver implementations, including @ExceptionHandler methods in @ControllerAdvice, to produce HTTP responses, potentially using ProblemDetail. Spring Boot also provides BasicErrorController as a fallback for otherwise unhandled web errors.

Could you say this in an interview?

1. Data access translation.

Without it, each technology throws its own exceptions: JDBC SQLException with vendor codes, Hibernate ConstraintViolationException, JPA PersistenceException. Spring maps them to one hierarchy, for example DuplicateKeyException, DataIntegrityViolationException, OptimisticLockingFailureException, QueryTimeoutException. Your service code can catch these without knowing the driver.

How it is wired in Spring Boot:

@AutoConfiguration
@ConditionalOnClass(PersistenceExceptionTranslationPostProcessor.class)
public final class PersistenceExceptionTranslationAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBooleanProperty(name = "spring.persistence.exceptiontranslation.enabled", matchIfMissing = true)
    static PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor(
            Environment environment) {
        PersistenceExceptionTranslationPostProcessor postProcessor = new PersistenceExceptionTranslationPostProcessor();
        ...
        return postProcessor;
    }
}

PersistenceExceptionTranslationAutoConfiguration.java L25-L41

The post-processor wraps every @Repository bean in a proxy. The proxy catches runtime exceptions and asks PersistenceExceptionTranslator beans (for example the JPA EntityManagerFactory bean) to translate them. JdbcTemplate translates SQLException itself with SQLExceptionTranslator, using SQL state and vendor error codes. Spring Data repositories get translation automatically.

try {
    repository.save(user);
} catch (DataIntegrityViolationException ex) {
    throw new EmailAlreadyUsedException(user.email());
}

2. Web exception handling.

  • @ExceptionHandler methods in a controller or a @ControllerAdvice class turn exceptions into responses.
  • ResponseStatusException or @ResponseStatus set a status code.
  • ProblemDetail gives RFC 9457 error bodies; Spring Boot enables it for Spring MVC's own exceptions with spring.mvc.problemdetails.enabled=true.
  • If nothing handles the error, Spring Boot's ErrorMvcAutoConfiguration provides a BasicErrorController mapped to /error, unless you define your own ErrorController (ErrorMvcAutoConfiguration.java L88-L95). It returns JSON for API clients and a "Whitelabel" page for browsers.
@RestControllerAdvice
class ApiErrors {
    @ExceptionHandler(EmailAlreadyUsedException.class)
    ProblemDetail conflict(EmailAlreadyUsedException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, ex.getMessage());
    }
}

Interview distinction: data-access translation changes the exception type inside the app; web handling changes the HTTP response. A good design uses both: translate at the repository, map to a domain exception in the service, and map that to an HTTP status at the edge.

Alternate interview scenarios

"Your API returns stack traces, leaks exception messages, or turns every error into 500. How do you design the error responses?"
Map errors at one edge, a @RestControllerAdvice, and return RFC 9457 problem details: type, title, status, detail and instance, plus a correlation ID, never a stack trace.

  • Spring Boot defaults. In Spring Boot 4 the /error properties live under spring.web.error.* (they were server.error.* in Spring Boot 3): include-stacktrace and include-message both default to never. Leaks usually come from changing those or from handlers that copy ex.getMessage() into the body.
  • ProblemDetail. Extending ResponseEntityExceptionHandler gives problem-detail bodies for Spring MVC's own exceptions; spring.mvc.problemdetails.enabled (default false) switches the same on without code.
  • Map by cause, not by type alone. A malformed JSON body (HttpMessageNotReadableException) or failed validation is the client's fault: 400. A domain conflict is 409. An upstream timeout is usually 504 Gateway Timeout when this service acts as a gateway, or 503 with Retry-After when it sheds load; a generic 500 hides that from clients and from alerts.
  • Log once. Log the exception with its cause at the edge, with the correlation ID, and do not also log it in every layer it passes.
"How would you optimize exception handling in the controller layer?"
I start by taking try/catch out of the controllers. One @RestControllerAdvice with @ExceptionHandler methods maps exceptions to responses, so every endpoint returns the same ProblemDetail body and the controllers only contain the happy path. Expected business cases get specific handlers and 4xx codes: not found is 404, validation failures are 400, and a version conflict is 409. One catch-all handler logs the stack trace once, with a request or trace id, and returns a generic 500 without internal details. I also stop logging the same exception at every layer, which is often the biggest log cost.

Then performance. An exception is not free: a Throwable holds a snapshot of the thread's stack from the moment it was created, and capturing that is real work on deep Spring call stacks. So for outcomes that are expected and frequent on a hot path, like "product not found" on a busy endpoint, I return an Optional or a result instead of throwing. When a domain exception is used purely as a signal, Throwable has a protected constructor that turns off the writable stack trace. I never do that for real failures, because the stack trace is exactly what you need to debug them.

Sources (8)
  1. Spring Framework reference: Consistent exception hierarchy and @Repositorydocs.spring.io
  2. Spring Framework reference: Exceptions in Spring MVCdocs.spring.io
  3. Spring Boot reference: Error handlingdocs.spring.io
  4. Spring Boot 4 application properties: spring.web.error.* and spring.mvc.problemdetails.enableddocs.spring.io
  5. Spring Framework reference: Error responses and ProblemDetaildocs.spring.io
  6. RFC 9457: Problem Details for HTTP APIsrfc-editor.org
  7. RFC 9110: 504 Gateway Timeoutrfc-editor.org
  8. Throwable Javadoc (Java 21): stack trace snapshot and writableStackTracedocs.oracle.com
Previous
Next