global error handling: what should your api do when it fails?
separate expected outcomes from unexpected failures, return safe problem details and connect the response to a server record with a trace id.
a checkout screen says “something went wrong”. the customer does not know whether the order was saved. the developer does not know which request to inspect. global error handling connects those concerns: it gives the client a predictable response and leaves a useful trail for investigation.
published: updated:

in this article
decide whether this is an outcome or a failure
a missing order, insufficient stock and a broken database connection require different decisions. the first two can be expected application outcomes. the connection failure prevents normal execution. turning all three into 500 responses hides whether the client can correct anything.
return 404 for a missing resource or 409 for a conflict with current state when that matches your contract. validation may use 400; authentication and authorization mechanisms produce their own 401 or 403 responses. spring boot 4 makes this distinction explicit through types such as ErrorResponseException and ResponseEntityExceptionHandler. never classify an unknown exception by searching its message for words such as “not found”.
explicit endpoint results are sufficient for many small applications. introduce a shared result model when application boundaries need it. our central handler deliberately handles unexpected failures as 500.
where a catch block belongs
copying the same try/catch into every endpoint eventually creates inconsistent responses and duplicate logs. place an exception handler early in the request pipeline to handle exceptions propagated from downstream code. in spring mvc the equivalent is a @RestControllerAdvice class: exceptions raised by code that runs after it are handled there.
local catch blocks still make sense when you can recover or translate a failure meaningfully. logging and rethrowing at every layer records the same incident repeatedly. use “throw exception;” when rethrowing to preserve the existing stack trace.
a complete request pipeline
create a project with spring initializr, choosing “spring boot” and “java 25”. add the “spring web” and “actuator” dependencies. place the files below under the source folder and run “mvn spring-boot:run”. no extra package is required. /demo/failure exists solely to demonstrate a failure; remove it from a real application.
order 42 returns 200 and other order ids return an empty 404. the latter does not throw and therefore does not enter the exception handler. the failure endpoint returns an application/problem+json response with a stable application code.
the correlation id filter generates an identifier when the request has none, writes it to the mdc and returns it as a response header. the advice class reads that value from the mdc, so the trace id sent to the client can be matched with the server record. exporting traces, storing them in a database or setting up opentelemetry is outside the scope of this example.
package com.example.errors;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.UUID;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.filter.OncePerRequestFilter;
@RestController
class OrderController {
@GetMapping("/orders/{id}")
ResponseEntity<Map<String, String>> order(@PathVariable int id) {
if (id != 42) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(Map.of("id", id, "status", "ready"));
}
@GetMapping("/demo/failure")
Map<String, String> failure() {
throw new IllegalStateException("Demo failure");
}
}
@Component
class CorrelationIdFilter extends OncePerRequestFilter {
static final String HEADER = "X-Correlation-Id";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String correlationId = request.getHeader(HEADER);
if (correlationId == null || correlationId.isBlank()) {
correlationId = UUID.randomUUID().toString();
}
MDC.put("traceId", correlationId);
response.setHeader(HEADER, correlationId);
try {
chain.doFilter(request, response);
} finally {
MDC.remove("traceId");
}
}
}
@RestControllerAdvice
class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(Exception.class)
ResponseEntity<ProblemDetail> handleUnexpected(Exception exception) {
String traceId = MDC.get("traceId");
// Record classification, not the exception's sensitive payload.
log.error("Request failed. ErrorCode={ErrorCode} ExceptionType={ExceptionType} TraceId={TraceId}",
"unexpected_error", exception.getClass().getSimpleName(), traceId);
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.INTERNAL_SERVER_ERROR, "The request could not be completed.");
problem.setTitle("Internal Server Error");
problem.setType(URI.create("about:blank"));
problem.setProperty("code", "unexpected_error");
problem.setProperty("traceId", traceId);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(problem);
}
}a safe response with a useful trail
exception messages and stack traces can contain paths, table names or sensitive upstream data. the client receives a fixed title and traceId instead. use that identifier to find the corresponding server record.
the example records the exception type without logging its payload. deeper diagnosis may require a restricted diagnostic channel with redaction and a retention policy. do not automatically capture request bodies, credentials or connection strings.
spring boot 4 can collect error rate metrics through actuator and micrometer, but that is a separate configuration step. a trace identifier alone does not configure an opentelemetry exporter or alerts.
the boundary of global handling
once a response has started, you cannot safely replace it with a new error body. streaming requires its own failure expectations. background jobs, message consumers and startup failures also sit outside this http middleware.
pass cancellation signals to dependent operations. a disconnected client, an application deadline and an upstream timeout are different events. inspect thread interruption before classifying cancellation as a server defect.
a failure response does not roll back completed work. a payment could succeed before the connection disappears. retries for such operations require a deliberate idempotency policy and transaction boundaries.
test failure as a public contract
send this request and expect 500 with status 500, code unexpected_error and a nonempty traceId. neither “Demo failure” nor a stack trace should appear in the body. match the traceId to a server record. check /orders/42 for 200 and /orders/999 for 404.
exercise the actual http pipeline in integration tests. invoking the advice method directly does not verify middleware order. @WebMvcTest isolates the advice behavior. verify that a healthy request still succeeds after the failing request.
in an operated service, test error rate alerts with a controlled fault. persistent audit records with tamper protection, distributed trace export and alert delivery require their own setup and verification. this demonstration does not claim to supply those facilities.
GET http://localhost:8080/demo/failure
Accept: application/problem+jsonfrequently asked questions
- how do i set up global error handling in spring boot?
- create a @restcontrolleradvice class with a central handler. an exception raised by code that runs after the handler is caught there. returning expected business outcomes directly from the endpoint is still the better approach; the central handler turns unexpected failures into a safe 500 response and a server record that carries the same trace id.
- which status code should each failure return?
- 404 for a missing resource, 409 for a conflicting state and 400 for input validation are contract decisions. authentication and authorization failures produce 401 and 403 through their own mechanisms. never convert an unknown exception into 404 only because its message mentions “not found”; that hides a software defect.
- what should a client receive when something fails?
- exception messages, stack traces, connection details and table names can carry sensitive data. the client receives a fixed title and a trace id, and that identifier leads you to the matching server record. a failure response also does not roll back completed work, so payments and similar operations need a deliberate idempotency policy and transaction boundaries.