Errors Intermediate

Use records for concise, immutable error response types.

โœ• 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());
    }
}
See a problem with this code? Let us know.
๐Ÿ“

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
Record-based error responses
Available

Widely available since JDK 16 (March 2021)

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.