Record-based error responses
Use records for concise, immutable error response types.
Porównanie kodu
✕ 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());
}
}
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
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.
Stare podejście
Map or Verbose Class
Nowoczesne podejście
Error Records
Od JDK
16
Poziom trudności
Średniozaawansowany
Wsparcie JDK
Record-based error responses
Dostępne
Widely available since JDK 16 (March 2021)
Jak to działa
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.
Powiązana dokumentacja