KatInterview

Uniform Error Responses in a Spring Banking API

System DesignModel answer
MediumModel answerSystem Designjavaspringexception-handling

Last 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

  1. Error contract. Define a class ErrorResponse with four fields: a timestamp, a numeric HTTP status, a readable message, and a unique trace identifier.
  2. Central handler. Write a class GlobalExceptionHandler annotated with @ControllerAdvice that intercepts:
    • UserNotFoundException
    • InsufficientFundsException
    • any other Exception as a fallback
  3. Status mapping. Use 404 Not Found for missing resources, 422 Unprocessable Entity for business-rule violations, and 500 Internal Server Error for unexpected failures.
  4. 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.