Uniform Error Responses in a Spring Banking API
System DesignModel answerLast updated
Design a centralized Spring exception handling layer that returns one JSON error contract, maps domain errors to HTTP codes, hides internals, and ties each response to server logs via a trace ID.
Context
You are working on a REST backend for a retail banking product written with Spring Boot. Failures can originate in controllers, services, or repository calls. Whatever the origin, API consumers must always receive the same JSON error shape, and nothing sensitive (stack traces, SQL fragments, hostnames, account data) may reach them.
What to build
- Error contract. Define a class
ErrorResponsewith four fields: a timestamp, a numeric HTTP status, a readable message, and a unique trace identifier. - Central handler. Write a class
GlobalExceptionHandlerannotated with@ControllerAdvicethat intercepts:UserNotFoundExceptionInsufficientFundsException- any other
Exceptionas a fallback
- Status mapping. Use
404 Not Foundfor missing resources,422 Unprocessable Entityfor business-rule violations, and500 Internal Server Errorfor unexpected failures. - Correlation. Explain briefly how the trace ID is created and logged so that the value a client sees can be found in the server logs for that exact request.
Example
When UserNotFoundException is thrown for user 123, the client gets HTTP 404 and:
{
"timestamp": "2023-10-27T10:00:00Z",
"status": 404,
"message": "User with ID 123 not found.",
"traceId": "a1-b2-c3-d4"
}
Expected answer
Provide the Java code for ErrorResponse and GlobalExceptionHandler (plus any helper you need for the trace ID), and discuss design trade-offs, cases the advice cannot catch, and common mistakes.
Hints
Hint 1
Error handling is a cross-cutting concern. Think about which Spring mechanism lets one class intercept exceptions from every controller, and how Spring chooses between a specific handler and a generic `Exception` handler.
Hint 2
The trace ID must exist before any service code logs anything. Consider a servlet filter that puts an ID into the logging MDC, so both your log lines and the error handler can read the same value.
Hint 3
For the catch-all, decide what the client may see versus what only the logs may contain. Also consider what happens to exceptions thrown outside Spring MVC, such as in security filters, and to framework exceptions like malformed JSON.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat error reporting as a cross-cutting concern and put it in one place. The design has three parts:
- A fixed contract:
ErrorResponsewithtimestamp,status,message,traceId. - A type-to-status mapping in a
@ControllerAdviceclass. Domain exceptions get precise statuses and client-safe messages. A catch-allExceptionhandler returns a generic 500 and never echoes the original message. - A correlation ID created by a filter at the start of the request, stored in the logging MDC, and read by the handler.
Code
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(long id) {
super("User with ID " + id + " not found.");
}
}
public class InsufficientFundsException extends RuntimeException {
public InsufficientFundsException(String accountId) {
super("Insufficient funds in account " + accountId + ".");
}
}
public class ErrorResponse {
private final Instant timestamp;
private final int status;
private final String message;
private final String traceId;
public ErrorResponse(HttpStatus status, String message, String traceId) {
this.timestamp = Instant.now();
this.status = status.value();
this.message = message;
this.traceId = traceId;
}
public Instant getTimestamp() { return timestamp; }
public int getStatus() { return status; }
public String getMessage() { return message; }
public String getTraceId() { return traceId; }
}
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TraceIdFilter extends OncePerRequestFilter {
public static final String MDC_KEY = "traceId";
public static final String HEADER = "X-Trace-Id";
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
FilterChain chain) throws ServletException, IOException {
String incoming = req.getHeader(HEADER);
String traceId = (incoming != null && incoming.matches("[A-Za-z0-9-]{1,64}"))
? incoming : UUID.randomUUID().toString();
MDC.put(MDC_KEY, traceId);
res.setHeader(HEADER, traceId);
try {
chain.doFilter(req, res);
} finally {
MDC.remove(MDC_KEY); // pooled threads: always clean up
}
}
}
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(UserNotFoundException ex) {
log.warn("Not found: {}", ex.getMessage());
return build(HttpStatus.NOT_FOUND, ex.getMessage());
}
@ExceptionHandler(InsufficientFundsException.class)
public ResponseEntity<ErrorResponse> handleFunds(InsufficientFundsException ex) {
log.warn("Business rule violated: {}", ex.getMessage());
return build(HttpStatus.UNPROCESSABLE_ENTITY, ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleUnexpected(Exception ex) {
log.error("Unhandled exception", ex); // stack trace stays in logs
return build(HttpStatus.INTERNAL_SERVER_ERROR,
"An unexpected error occurred. Please contact support with the trace ID.");
}
private ResponseEntity<ErrorResponse> build(HttpStatus status, String message) {
String traceId = Optional.ofNullable(MDC.get(TraceIdFilter.MDC_KEY))
.orElseGet(() -> UUID.randomUUID().toString());
return ResponseEntity.status(status)
.contentType(MediaType.APPLICATION_JSON)
.body(new ErrorResponse(status, message, traceId));
}
}
Logging pattern so every line carries the ID:
%d{ISO8601} %-5level [%X{traceId}] %logger{36} - %msg%n
Why this works
- Single contract. All handlers go through
build(...), so the JSON shape cannot drift. - Most specific handler wins. Spring selects the handler whose exception type is closest to the thrown type, so
UserNotFoundExceptionnever falls into theExceptioncatch-all. - No leaks. The fallback discards
ex.getMessage()(which could contain SQL, hostnames or account details) and returns fixed text. The stack trace is written only to the server log. - Correlation. The filter runs before the
DispatcherServlet, so the MDC already has the ID when service code logs and when the handler runs. Support can search the client'straceIdin the log platform and see the whole request. Accepting a validated upstreamX-Trace-Idlets the ID follow a call across microservices; the regex prevents log injection.
Trade-offs and choices
- Message safety for domain exceptions. Returning
ex.getMessage()is fine only if domain exception messages are written to be client-safe. An alternative is an error code enum plus a message catalog, which also supports localization. - Status choice. 422 fits a well-formed request that violates a business rule. Some teams prefer 409 for state conflicts; pick one convention and document it.
- Logging levels. Expected business errors are
warn(orinfo) without stack traces; unexpected ones areerrorwith the full trace. This keeps alerting meaningful. - Alternatives. Spring 6 supports
ProblemDetail(RFC 7807/9457), which standardizes the contract; you can extend it with atraceIdproperty. Tracing libraries (Micrometer Tracing, OpenTelemetry) can supply the ID instead of a hand-written filter.
Cost
Handler lookup is cached by Spring, so it is effectively O(1) amortized per exception. UUID generation and MDC operations are O(1) per request, so the overhead is negligible.
Edge cases and common mistakes
- Exceptions outside MVC. Errors thrown in servlet filters (for example, security) occur before dispatch, so
@ControllerAdvicenever sees them. Use a Spring SecurityAuthenticationEntryPointandAccessDeniedHandler, or a customErrorController, that emit the sameErrorResponse. - Framework exceptions.
HttpMessageNotReadableException(bad JSON),MethodArgumentNotValidException(validation), andHttpRequestMethodNotSupportedExceptionshould be mapped explicitly to 400 or 405. Otherwise the catch-all turns them into misleading 500s. ExtendingResponseEntityExceptionHandleris a convenient base. - Leaking details. Returning
ex.getMessage()orex.toString()from the generic handler is the most frequent mistake. - MDC leaks. Forgetting to clear the MDC in a
finallyblock lets a pooled thread reuse a stale ID on a later request. For async work (@Async, executors), the MDC must be copied explicitly, for example with aTaskDecorator. - Swallowing exceptions. Catching and logging without rethrowing in services hides failures from the advice. Let exceptions propagate.
- Duplicate logging. Logging the same exception in the service and again in the handler produces noise; log at the boundary.
- Different IDs. Generating a fresh UUID inside the handler when the MDC is empty gives the client an ID that matches no earlier log line. The fallback is acceptable only as a last resort, and the handler's own log line should still carry it.
- Testing. Cover the handler with
@WebMvcTestandMockMvc: assert status, JSON fields, that the 500 body contains no exception text, and that the responseX-Trace-Idheader equals the body'straceId.