Production-Grade Spring Boot APIs — Part 3: Consistent Responses & Global Exception Handling
Source: Dev.to
Why API response consistency matters in microservices
- APIs must look identical across services.
- Errors must be predictable.
- Clients should never have to guess the response format.
Without discipline you end up with:
- Different response formats per endpoint
- Unclear error messages
- Controllers full of
try‑catchblocks
Designing a generic BaseResponse
A generic wrapper lets you standardize both success and error payloads.
public class BaseResponse<T> {
private int status;
private String message;
private T data;
// getters, setters, builder, etc.
}
Builder pattern in API responses
Using the builder makes the response readable, safe, scalable, and uniform.
BaseResponse<String> response = BaseResponse.builder()
.status(200)
.message("Success")
.data("Hello")
.build();
Benefits
- Uniform success responses
- Uniform error responses
- Easy API evolution
ResponseEntity and real HTTP semantics
ResponseEntity represents the entire HTTP response:
- Status code
- Headers
- Body
APIs should communicate using proper HTTP semantics, not just JSON bodies.
Global exception handling with @RestControllerAdvice
Centralizing error handling keeps controllers clean and lets services throw domain‑specific exceptions.
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<BaseResponse<?>> handleNotFound(ResourceNotFoundException ex) {
BaseResponse<?> body = BaseResponse.builder()
.status(HttpStatus.NOT_FOUND.value())
.message(ex.getMessage())
.build();
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(body);
}
// other exception handlers …
}
- Controllers stay clean.
- Services throw domain exceptions.
- Errors are handled centrally.
- One response format, one place, zero duplication.
Conclusion
The structure described above is what we use in real Spring Boot microservices:
- Clean layers
- Explicit dependencies
- Consistent APIs
- Interview‑defensible design
Production‑grade Spring Boot is less about annotations and more about discipline and structure. This article concludes the Production‑Grade Spring Boot API Design series, based on real project experience and refined personal notes.