forked from javaevolved/javaevolved.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecord-based-errors.json
More file actions
54 lines (54 loc) · 1.91 KB
/
Copy pathrecord-based-errors.json
File metadata and controls
54 lines (54 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
{
"id": 69,
"slug": "record-based-errors",
"title": "Record-based error responses",
"category": "errors",
"difficulty": "intermediate",
"jdkVersion": "16",
"oldLabel": "Java 8",
"modernLabel": "Java 16+",
"oldApproach": "Map or Verbose Class",
"modernApproach": "Error Records",
"oldCode": "// Verbose error class\npublic class ErrorResponse {\n private final int code;\n private final String message;\n // constructor, getters, equals,\n // hashCode, toString...\n}",
"modernCode": "public record ApiError(\n int code,\n String message,\n Instant timestamp\n) {\n public ApiError(int code, String msg) {\n this(code, msg, Instant.now());\n }\n}",
"summary": "Use records for concise, immutable error response types.",
"explanation": "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.",
"whyModernWins": [
{
"icon": "📏",
"title": "Concise",
"desc": "Define error types in 3 lines instead of 30."
},
{
"icon": "🔒",
"title": "Immutable",
"desc": "Error data can't be accidentally modified after creation."
},
{
"icon": "📋",
"title": "Auto toString",
"desc": "Perfect for logging — shows all fields automatically."
}
],
"support": {
"state": "available",
"description": "Widely available since JDK 16 (March 2021)"
},
"prev": "errors/null-in-switch",
"next": "errors/optional-orelsethrow",
"related": [
"errors/helpful-npe",
"errors/require-nonnull-else",
"errors/multi-catch"
],
"docs": [
{
"title": "Records (JEP 395)",
"href": "https://openjdk.org/jeps/395"
},
{
"title": "Record class",
"href": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Record.html"
}
]
}