Skip to content

Commit

Permalink
adds null check and throws EvaluationException when accessing undefin…
Browse files Browse the repository at this point in the history
…ed structure values (#350)

adds null check and throws EvaluationException when accessing undefined structure values
  • Loading branch information
uklimaschewski authored Feb 12, 2023
1 parent 4073767 commit 3d9c1a0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/main/java/com/ezylang/evalex/Expression.java
Original file line number Diff line number Diff line change
Expand Up @@ -186,9 +186,14 @@ private EvaluationValue evaluateArrayIndex(ASTNode startNode) throws EvaluationE

private EvaluationValue evaluateStructureSeparator(ASTNode startNode) throws EvaluationException {
EvaluationValue structure = evaluateSubtree(startNode.getParameters().get(0));
String name = startNode.getParameters().get(1).getToken().getValue();
Token nameToken = startNode.getParameters().get(1).getToken();
String name = nameToken.getValue();

if (structure.isStructureValue()) {
if (!structure.getStructureValue().containsKey(name)) {
throw new EvaluationException(
nameToken, String.format("Field '%s' not found in structure", name));
}
return structure.getStructureValue().get(name);
} else {
throw EvaluationException.ofUnsupportedDataTypeInOperation(startNode.getToken());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,17 @@ void testThrowsUnsupportedDataTypeForStructure() {
.isInstanceOf(EvaluationException.class)
.hasMessage("Unsupported data types in operation");
}

@Test
void testThrowsFieldNotFound() {
Map<String, BigDecimal> testStructure = new HashMap<>();
testStructure.put("field1", new BigDecimal(3));

assertThatThrownBy(
() -> createExpression("a.field1 + a.field2").with("a", testStructure).evaluate())
.isInstanceOf(EvaluationException.class)
.hasMessage("Field 'field2' not found in structure")
.extracting("startPosition")
.isEqualTo(14);
}
}

0 comments on commit 3d9c1a0

Please sign in to comment.