โ— Shell
clean mode source โ†—

Record-based error responses

Home / Errors / Record-based error responses

Code Comparison

// Verbose error class
public class ErrorResponse {
    private final int code;
    private final String message;
    // constructor, getters, equals,
    // hashCode, toString...
}
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

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.

Related Documentation

Proof