Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

Your REST services return stack traces in error responses in some cases and generic 500s with no detail in others. How do you design consistent error handling for a Spring Boot service?

Handle every exception centrally in one @RestControllerAdvice that extends ResponseEntityExceptionHandler, and return RFC 9457 problem details through Spring's ProblemDetail with a type, title, status and a stable error code. Never return stack traces or internal messages; log them on the server with a correlation ID and put that ID in the response. Map validation and domain errors to 4xx, infrastructure failures to 5xx or 503 with retry guidance, and test the error responses as part of the API contract.

Why this question is asked

Error responses are part of an API just as much as success responses. When some endpoints leak stack traces and others return a bare 500, clients cannot handle errors reliably, support cannot connect a complaint to a log line, and attackers learn about our internals. Interviewers ask this scenario to see whether we know the pieces Spring Boot provides and can turn them into one consistent design. In this answer, we will see why responses become inconsistent, design a single handler, define the response format, decide the status mapping, connect responses to logs with a correlation ID, and lock it down with tests.

1Why the Responses Are Inconsistent Today

In a Spring Boot service, an exception thrown by a controller can end up in several different places. If a @ControllerAdvice or @ExceptionHandler handles it, that code decides the response, and a hand-written one may return e.getMessage() or even the stack trace. If nothing handles it, Spring Boot's fallback error controller, BasicErrorController, renders a response from the server.error.* settings. server.error.include-stacktrace defaults to never, but it is easy to set it to always for debugging and forget, and Spring Boot DevTools turns on detailed error output in development (check your version for the exact properties).

Meanwhile, Spring MVC's own exceptions, such as a malformed JSON body or a missing request parameter, are handled by default resolvers with their own format. So three code paths produce three formats, and which one a client gets depends on where the failure happened. That is exactly the mix described in the question.

2One Central Handler

The fix is one class that handles everything. Extending ResponseEntityExceptionHandler gives us Spring MVC's built-in exceptions already mapped to problem details with the right statuses; we add handlers for our domain exceptions and a catch-all for everything else. Alternatively, setting spring.mvc.problemdetails.enabled=true makes Spring Boot register such a handler for the built-in exceptions automatically.

Java
@RestControllerAdvice
class ApiExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(OrderNotFoundException.class)
ProblemDetail notFound(OrderNotFoundException ex) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, "Order not found");
pd.setType(URI.create("https://api.example.com/errors/order-not-found"));
pd.setProperty("code", "ORDER_NOT_FOUND");
pd.setProperty("orderId", ex.orderId());
return withCorrelationId(pd);
}
@ExceptionHandler(DependencyUnavailableException.class)
ResponseEntity<ProblemDetail> unavailable(DependencyUnavailableException ex) {
log.warn("Dependency unavailable", ex);
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.SERVICE_UNAVAILABLE, "Please retry shortly");
pd.setProperty("code", "DEPENDENCY_UNAVAILABLE");
return ResponseEntity.status(503).header(HttpHeaders.RETRY_AFTER, "10").body(withCorrelationId(pd));
}
@ExceptionHandler(Exception.class)
ProblemDetail unexpected(Exception ex) {
log.error("Unhandled exception", ex); // full trace stays on the server
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, "Internal error");
pd.setProperty("code", "INTERNAL_ERROR");
return withCorrelationId(pd); // no message, no class name, no trace
}
private ProblemDetail withCorrelationId(ProblemDetail pd) {
pd.setProperty("correlationId", MDC.get("correlationId"));
return pd;
}
}

Notice the catch-all handler. It is what turns the generic, detail-free 500 into something useful without leaking anything: the client gets a stable code and a correlation ID, and the server log gets the full trace under the same ID.

3The Response Format: RFC 9457 Problem Details

RFC 9457, which replaced RFC 7807, defines a standard JSON body for HTTP errors with the media type application/problem+json. Its standard fields are type (a URI that identifies the kind of problem), title (a short human summary), status, detail (a human explanation of this occurrence) and instance (the request it relates to). Any extra fields are allowed, so we add our own stable code and the correlation ID.

YAML
HTTP/1.1 404 Not Found
Content-Type: application/problem+json
{
"type": "https://api.example.com/errors/order-not-found",
"title": "Not Found",
"status": 404,
"detail": "Order not found",
"instance": "/orders/A-17",
"code": "ORDER_NOT_FOUND",
"orderId": "A-17",
"correlationId": "7f3c9a2e41b8"
}

Clients match on type or code, never on detail, which is free text that we may reword. Using the standard means generic client libraries and API gateways already know how to read our errors.

4Choosing the Status Codes

The status tells the client whose problem it is and whether trying again makes sense. Errors caused by the request, such as invalid input, a missing resource or a conflict with the current state, are 4xx: retrying the same request will not help. Failures on our side are 5xx. Among those, 503 Service Unavailable with a Retry-After header says that the problem is temporary, for example a database failover or an open circuit breaker, which lets well-behaved clients back off and retry.

Mapping exceptions to responses
ExceptionStatusCodeRetry?
MethodArgumentNotValidException400VALIDATION_FAILED, with field errorsno, fix input
HttpMessageNotReadableException400MALFORMED_BODYno
OrderNotFoundException404ORDER_NOT_FOUNDno
OptimisticLockingFailureException409CONCURRENT_UPDATEafter re-reading
DependencyUnavailableException503 + Retry-AfterDEPENDENCY_UNAVAILABLEyes, with backoff
anything else500INTERNAL_ERRORreport the correlation ID
The table is part of the API documentation, not just the code.

5Connecting Responses to Logs

A correlation ID is a unique value attached to each request, often taken from an incoming header such as a trace ID or generated by a servlet filter, and stored in the MDC so every log line for that request includes it. When the error handler puts the same value in the response, a client can quote it in a support ticket and an engineer can find every log line for that request in seconds. With Micrometer Tracing, the trace ID can serve as the correlation ID.

This is what makes it safe to return nothing internal. The client does not need the stack trace; it needs a stable code and a way to refer to the failure. The details live in the logs, where only we can see them. As a safety net, we also make sure server.error.include-stacktrace and include-message are never set to always in production configuration.

6Testing Errors as Part of the Contract

Error responses break silently when someone adds a new exception or changes a handler, so we test them like any other response. MockMvc tests in a @WebMvcTest slice can trigger each error and assert the status, the content type and the fields.

Java
@Test
void unknownOrderReturnsProblemDetail() throws Exception {
given(orders.find("A-17")).willThrow(new OrderNotFoundException("A-17"));
mvc.perform(get("/orders/A-17"))
.andExpect(status().isNotFound()) // 404
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.code").value("ORDER_NOT_FOUND"))
.andExpect(jsonPath("$.correlationId").exists())
.andExpect(jsonPath("$.trace").doesNotExist()); // never leak a stack trace
}

If the API is described with OpenAPI, the error schemas belong there too, and contract tests for consumers can check them. A test that throws a plain RuntimeException and asserts that the body contains no exception class name is a cheap guard against leaks.

7Follow-up questions

Should validation errors be 400 or 422?

Both are used. 400 Bad Request is the most common choice and is what Spring returns for bean validation failures by default. 422 Unprocessable Content is sometimes used for input that is well-formed but semantically invalid. The important thing is to decide once for the whole API and document it.

Where do errors from filters or Spring Security go?

Exceptions thrown before the request reaches a controller, for example in a servlet filter or in Spring Security's authentication, are not seen by @RestControllerAdvice. Spring Security has its own AuthenticationEntryPoint and AccessDeniedHandler, which we configure to write the same problem detail format, so 401 and 403 responses match the rest.

How does this work in WebFlux?

The same ideas apply. Spring WebFlux also supports @RestControllerAdvice and ProblemDetail, has a reactive ResponseEntityExceptionHandler, and Spring Boot offers spring.webflux.problemdetails.enabled for the built-in exceptions.

8Conclusion

In this answer, we saw that inconsistent errors come from several code paths: hand-written handlers, Spring's default resolvers and Spring Boot's fallback error controller. We replaced them with one @RestControllerAdvice extending ResponseEntityExceptionHandler that returns RFC 9457 problem details with a stable code, mapped client errors to 4xx and infrastructure failures to 5xx or 503 with Retry-After, kept stack traces in server logs linked by a correlation ID in the response, and tested error responses as part of the API contract.

What to say in the interviewAbout 80 seconds aloud

Open with

The inconsistency comes from errors taking different paths: some handled by hand-written handlers that return the message or the trace, some falling through to Spring Boot's BasicErrorController, and some handled by Spring MVC's default resolvers.

Then, if they want more

I would replace all of that with one @RestControllerAdvice that extends ResponseEntityExceptionHandler, so Spring's own exceptions, like validation and unreadable bodies, are already mapped, and I add handlers for our domain exceptions plus a catch-all for Exception.

Every response is an RFC 9457 problem detail using Spring's ProblemDetail, with type, title, status and detail, plus a stable error code clients can match on and a correlation ID. Validation and domain errors map to 4xx: 400, 404, 409. Dependency failures map to 503 with a Retry-After header, and anything unexpected is a 500 with only a generic message.

Stack traces and internal messages never go to clients; the catch-all logs the full exception with the correlation ID, which comes from a filter and the MDC, so support can find the logs from the ID in the response. I would also make sure server.error.include-stacktrace is never always in production.

Finally, I test error responses in @WebMvcTest tests, asserting the status, the problem JSON content type, the code, and that no trace is present.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Your REST services return stack traces in error responses in some cases and generic 500s...": https://scrivio-interview-library.netlify.app/java/exceptions/4d676c6530/