Skip to content

Commit 2961549

Browse files
committed
refactor: Guarantee non-null errors and depth-sort on raw pointers
1 parent faf6c3a commit 2961549

2 files changed

Lines changed: 14 additions & 8 deletions

File tree

src/main/java/com/retailsvc/http/internal/ProblemDetail.java

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,12 @@
1818
public record ProblemDetail(
1919
String type, String title, int status, String detail, List<Entry> errors) {
2020

21+
public ProblemDetail {
22+
if (errors == null) {
23+
errors = List.of();
24+
}
25+
}
26+
2127
/** One validation failure: its body location, the failed keyword, and a human-readable detail. */
2228
public record Entry(String pointer, String keyword, String detail) {}
2329

@@ -38,20 +44,20 @@ public static ProblemDetail forBadRequest(BadRequestException e) {
3844

3945
/**
4046
* Flattens a validation error into ordered {@code errors} entries: the failed branches of a
41-
* combinator (one each), or the single leaf otherwise. Multi-entry results are sorted deepest
47+
* combinator (one each), or the single leaf otherwise. Multiple sources are sorted deepest
4248
* pointer first (most-likely-intended branch) and de-duplicated on exact equality.
4349
*/
4450
private static List<Entry> entriesOf(ValidationError e) {
4551
List<ValidationError> sources = e.branches().isEmpty() ? List.of(e) : e.branches();
46-
List<Entry> entries = new ArrayList<>(sources.size());
52+
if (sources.size() > 1) {
53+
sources = new ArrayList<>(sources);
54+
sources.sort(Comparator.comparingInt((ValidationError s) -> depth(s.pointer())).reversed());
55+
}
56+
LinkedHashSet<Entry> entries = new LinkedHashSet<>();
4757
for (ValidationError s : sources) {
4858
entries.add(new Entry(fragment(s.pointer()), s.keyword(), s.message()));
4959
}
50-
if (entries.size() <= 1) {
51-
return entries;
52-
}
53-
entries.sort(Comparator.comparingInt((Entry en) -> depth(en.pointer())).reversed());
54-
return new ArrayList<>(new LinkedHashSet<>(entries));
60+
return new ArrayList<>(entries);
5561
}
5662

5763
private static String fragment(String pointer) {

src/main/java/com/retailsvc/http/internal/ProblemDetailRenderer.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ public static byte[] renderJson(ProblemDetail pd) {
3333

3434
private static void appendErrors(
3535
StringBuilder out, boolean first, List<ProblemDetail.Entry> errors) {
36-
if (errors == null || errors.isEmpty()) {
36+
if (errors.isEmpty()) {
3737
return;
3838
}
3939
if (!first) {

0 commit comments

Comments
 (0)