Skip to content

Commit

Permalink
More detailed exception when JSON parsing (#2941)
Browse files Browse the repository at this point in the history
Signed-off-by: Olivier Perrin <olivier.perrin@rte-france.com>
  • Loading branch information
olperr1 committed Mar 19, 2024
1 parent 381a4c0 commit 4ae9955
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions commons/src/main/java/com/powsybl/commons/json/JsonReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ public void readChildNodes(ChildNodeReader childNodeReader) {
contextQueue.add(new Context(ContextType.OBJECT, parser.currentName()));
childNodeReader.onStartNode(contextQueue.getLast().getFieldName());
}
default -> throw new PowsyblException("JSON parsing: unexpected token '" + parser.currentToken() + "' after field name");
default -> throw newUnexpectedTokenException();
}
}
case START_OBJECT -> {
Expand All @@ -257,7 +257,7 @@ public void readChildNodes(ChildNodeReader childNodeReader) {
contextQueue.removeLast();
}
case END_OBJECT -> throw new PowsyblException("JSON parsing: unexpected END_OBJECT");
default -> throw new PowsyblException("JSON parsing: unexpected token '" + parser.currentToken() + "'.");
default -> throw newUnexpectedTokenException();
}
}

Expand All @@ -272,14 +272,24 @@ public void readChildNodes(ChildNodeReader childNodeReader) {
private Context checkNodeChain(ContextType expectedNodeType) {
return Optional.ofNullable(contextQueue.peekLast())
.filter(n -> n.getType() == expectedNodeType)
.orElseThrow(() -> new PowsyblException("JSON parsing: unexpected " + parser.currentToken()));
.orElseThrow(this::newUnexpectedTokenException);
}

private PowsyblException newUnexpectedTokenException() {
try {
return new PowsyblException("JSON parsing: unexpected token '" + parser.currentToken() + "'" +
" (value = '" + parser.getValueAsString() + "')" +
" after field name '" + parser.currentName() + "'");
} catch (IOException e) {
return new PowsyblException("JSON parsing: unexpected " + parser.currentToken());
}
}

@Override
public void readEndNode() {
try {
if (getNextToken() != JsonToken.END_OBJECT) {
throw new PowsyblException("JSON parsing: unexpected token " + parser.currentToken());
throw newUnexpectedTokenException();
}
checkNodeChain(ContextType.OBJECT);
contextQueue.removeLast();
Expand Down

0 comments on commit 4ae9955

Please sign in to comment.