GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • →

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — Record-based error responses | java.evolved

Home / Errors / Record-based error responses
Errors Intermediate

Record-based error responses

  • 🐛 Report a code issue
  • 🌐 Report a translation issue
  • 💡 Suggest a new pattern

Use records for concise, immutable error response types.

Records
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());
    }
}
Share 𝕏
See a problem with this code? Let us know.
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.

Related Documentation
Records (JEP 395) ↗ Record class ↗
Proof
View proof source ↗
Related patterns
Errors Beginner

Helpful NullPointerExceptions

Java 8
// Old NPE message:
// "NullPointerException"
// at MyApp.main(MyApp.java:42)
// Which variable was null?!
Java 14+
// Modern NPE message:
// Cannot invoke "String.length()"
// because "user.address().city()"
// is null
// Exact variable identified!
Hover to see modern ➜
JDK 14+ →
Errors Beginner

Objects.requireNonNullElse()

Java 8
String name = input != null
    ? input
    : "default";
// easy to get the order wrong
Java 9+
String name = Objects
    .requireNonNullElse(
        input, "default"
    );
Hover to see modern ➜
JDK 9+ →
Errors Beginner

Multi-catch exception handling

Pre-Java 7
try {
    process();
} catch (IOException e) {
    log(e);
} catch (SQLException e) {
    log(e);
} catch (ParseException e) {
    log(e);
}
Java 7+
try {
    process();
} catch (IOException
    | SQLException
    | ParseException e) {
    log(e);
}
Hover to see modern ➜
JDK 7+ →
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.