Record-based error responses
Use records for concise, immutable error response types.
Code Comparison
✕ Java 8
// Verbose error class
public class ErrorResponse {
private final int code;
private final String message;
// constructor, getters, equals,
// hashCode, toString...
}
✓ Java 16+
public record ApiError(
int code,
String message,
Instant timestamp
) {
public ApiError(int code, String msg) {
this(code, msg, Instant.now());
}
}
Why the modern way wins
Concise
Define error types in 3 lines instead of 30.
Immutable
Error data can't be accidentally modified after creation.
Auto toString
Perfect for logging — shows all fields automatically.
Old Approach
Map or Verbose Class
Modern Approach
Error Records
Since JDK
16
Difficulty
intermediate
JDK Support
Record-based error responses
Available
Widely available since JDK 16 (March 2021)
How it works
Records are perfect for error responses — they're immutable, have built-in equals/hashCode for comparison, and toString for logging. Custom constructors add validation or defaults.