Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More detailed exceptions when parsing a JSON network #2941

Merged
merged 1 commit into from
Mar 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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