Production-Style Error Handling
Production error handling is a contract between the application, its operators, and its clients. A correct implementation returns a meaningful status, logs enough diagnostic context, avoids leaking internals, and gives support a way to connect related events.

Status is part of the API
Use 400 Bad Request when the client sent invalid data, 404 Not Found when a requested resource does not exist, and 409 Conflict when the request conflicts with the current state, such as creating a duplicate email. Use 500 Internal Server Error for an unexpected server failure. Do not return 500 for every exception simply because it was thrown in Java.
| Situation | Status | Public response |
|---|---|---|
| malformed or invalid input | 400 | validation code and field context |
| missing user or order | 404 | stable not-found code |
| duplicate or conflicting state | 409 | conflict code and safe message |
| unexpected defect | 500 | generic error and request ID |
Logs and responses have different audiences
A log is for operators; an error response is for the client. Log the exception type, stack trace, operation, authenticated subject when allowed, and a correlation/request ID. Never log passwords, access tokens, full payment data, or sensitive personal data. The public response should contain a stable code, safe message, path, timestamp if useful, and request ID.
@ExceptionHandler(Exception.class)
ResponseEntity<ErrorResponse> unexpected(
Exception ex, HttpServletRequest request) {
String requestId = request.getHeader("X-Request-Id");
log.error("Unhandled error requestId={} path={}",
requestId, request.getRequestURI(), ex);
return ResponseEntity.internalServerError()
.body(new ErrorResponse(
"INTERNAL_ERROR", "Unexpected server error", requestId));
}
Do not return ex.getMessage() for an unknown exception: it may contain SQL, file paths, or implementation details. Error codes should remain stable even when wording and localization change. A request ID lets an operator find the matching server event without exposing the full stack trace.
A practical decision sequence
- Classify the failure by the contract it violated.
- Choose the HTTP status that describes the client-visible meaning.
- Select a stable error code.
- Log the technical cause with a request ID.
- Return only safe public fields.
- Test status, body, and absence of sensitive details.
Glossary
- bytecode
- Platform-independent compiled code that the JVM can execute.
- class
- A blueprint that defines fields and methods for objects in object-oriented programming.
- object
- A runtime instance of a class with its own state and behavior.
- method
- A named block of behavior that belongs to a class or object and can be called by code.
- field
- A variable stored inside a class or object that represents part of its state.
- constructor
- A special method-like block used to create and initialize a new object.
- package
- A namespace that groups related Java classes and helps organize code.
- interface
- A contract that defines methods a class can implement without prescribing all internal details.
- generics
- A language feature that lets code work with types as parameters while preserving type safety.
- type erasure
- The Java compiler process that removes most generic type details from runtime bytecode.
- collection
- A data structure that stores a group of elements and provides operations over them.
- list
- An ordered collection where elements have positions and duplicates are allowed.
- set
- A collection that stores unique elements and is commonly used for membership checks.
- map
- A key-value data structure where each key points to a value.
- queue
- A collection designed for processing elements in a defined order, often first-in-first-out.
- lambda
- A compact function-like expression used to pass behavior as data.
- functional interface
- An interface with one abstract method, suitable for lambdas and method references.
- stream
- A Java API for processing data sequences with operations such as map, filter, and reduce.
- optional
- A container object that represents a value that may or may not be present.
- thread
- An independent path of execution inside a running program.
- synchronization
- Coordination that protects shared data when multiple threads access it.
- heap
- The runtime memory area where Java objects are allocated.
- stack
- The runtime memory area that stores method calls, local variables, and call frames.
- garbage collector
- A JVM component that automatically frees memory occupied by objects no longer reachable.
- memory leak
- A situation where memory remains occupied because objects are still referenced but no longer useful.