Skip to content

Commit 792c6f6

Browse files
committed
improved failure handling
1 parent 5bee7e3 commit 792c6f6

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

JSONPointer.java

+13-4
Original file line numberDiff line numberDiff line change
@@ -53,18 +53,27 @@ public Object queryFrom(JSONObject document) {
5353
if (current instanceof JSONObject) {
5454
current = ((JSONObject) current).opt(unescape(token));
5555
} else if (current instanceof JSONArray) {
56-
current = readByIndexToken(current, unescape(token));
56+
current = readByIndexToken(current, token);
57+
} else {
58+
throw new JSONPointerException(format(
59+
"value [%s] is not an array or object therefore its key %s cannot be resolved", current,
60+
token));
5761
}
5862
}
5963
return current;
6064
}
6165

6266
private Object readByIndexToken(Object current, String indexToken) {
6367
try {
64-
return ((JSONArray) current).opt(Integer.parseInt(unescape(indexToken)));
68+
int index = Integer.parseInt(indexToken);
69+
JSONArray currentArr = (JSONArray) current;
70+
if (index >= currentArr.length()) {
71+
throw new JSONPointerException(format("index %d is out of bounds - the array has %d elements", index,
72+
currentArr.length()));
73+
}
74+
return currentArr.get(index);
6575
} catch (NumberFormatException e) {
66-
throw new JSONPointerException(format("%s is not an array index", unescape(indexToken)), e);
76+
throw new JSONPointerException(format("%s is not an array index", indexToken), e);
6777
}
6878
}
69-
7079
}

0 commit comments

Comments
 (0)