GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing javaevolved.dev — Record-based error responses | java.evolved
Errors
Intermediate
Record-based error responsesUse 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());
}
}
See a problem with this code? Let us know.
Why the modern way wins
📏
ConciseDefine error types in 3 lines instead of 30. 🔒
ImmutableError data can't be accidentally modified after creation. 📋
Auto toStringPerfect 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
Proof
Related patterns
Errors
Beginner
Helpful NullPointerExceptionsJava 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!
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"
);
JDK 9+
→
Errors
Beginner
Multi-catch exception handlingPre-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);
}
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. |