An API should return errors in a consistent, machine-readable shape. The Problem Details format (RFC 7807, application/problem+json) provides a standard structure with a type, title, status and detail, which clients can handle uniformly instead of parsing ad-hoc error strings.
Before you start
You should be comfortable with @ControllerAdvice and HTTP status codes. This article covers a consistent error contract.
Step-by-step walkthrough
Step 1: Map exceptions centrally
Handle exceptions in a @ControllerAdvice so every controller returns the same shape. Mapping a domain exception to a status and a problem body keeps the error contract in one place, rather than scattered try/catch.
Step 2: Use the standard fields
Return type, title, status, detail and optionally instance, and add custom fields for validation errors. Clients can then branch on type or status predictably. Spring’s problem-details support can build the body from an exception.
Step 3: Do not leak internals
The detail should be safe for a client, not a stack trace or a database error. Log the full exception server-side and return a generic message plus a correlation id, so support can find the details without exposing them.
Worked scenario
The advice returns a consistent problem body.
@ExceptionHandler(OrderNotFound.class)
public ProblemDetail handle(OrderNotFound ex) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(
HttpStatus.NOT_FOUND, "Order not found");
pd.setTitle("Resource not found");
pd.setType(URI.create("https://errors.example.com/not-found"));
return pd;
}Walk through the example
The handler converts the domain exception into a 404 problem body with a stable type and a safe detail, so clients get a predictable shape. The full exception is logged elsewhere. Every controller that throws OrderNotFound returns the same contract.
Common mistake
Returning raw exception messages or stack traces, which leak internals, or a different error shape per endpoint, which forces clients to special-case. Another is returning 200 with an error body, which breaks client status handling.
Verify the behavior
Trigger each mapped exception and confirm the status and problem body match the contract. Assert the shape is identical across endpoints. Confirm no stack trace or SQL detail appears in the response.
Interview exercise
Why avoid returning the exception message directly?
Answer and reasoning
Because it can leak implementation details such as SQL, table names or file paths, which help an attacker and confuse users. Return a safe, human-readable detail and log the real exception with a correlation id. Support can trace the id; the client never sees internals.
Continue learning
Compare error handling in Exception advice and request checks in Request validation. Read the RFC 7807 problem details specification and try the Spring Boot interview questions.