From decfa55eaafafa1f5f5e8fef29e1fccf072a3b6a Mon Sep 17 00:00:00 2001 From: Manhey Chiu Date: Wed, 5 Jun 2024 08:09:30 +0100 Subject: [PATCH] Add InvalidInput error when ArithmeticException is thrown when resolving expression --- .../jinjava/el/ExpressionResolver.java | 14 ++++++++++++++ .../jinjava/el/ExpressionResolverTest.java | 19 ++++++++++++------- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/hubspot/jinjava/el/ExpressionResolver.java b/src/main/java/com/hubspot/jinjava/el/ExpressionResolver.java index a91dfba71..da810555c 100644 --- a/src/main/java/com/hubspot/jinjava/el/ExpressionResolver.java +++ b/src/main/java/com/hubspot/jinjava/el/ExpressionResolver.java @@ -188,6 +188,20 @@ private Object resolveExpression(String expression, boolean addToResolvedExpress interpreter.addError(TemplateError.fromInvalidInputException(e)); } catch (InvalidArgumentException e) { interpreter.addError(TemplateError.fromInvalidArgumentException(e)); + } catch (ArithmeticException e) { + interpreter.addError( + TemplateError.fromInvalidInputException( + new InvalidInputException( + interpreter, + ExpressionResolver.class.getName(), + String.format( + "ArithmeticException when resolving expression [%s]: " + + getRootCauseMessage(e), + expression + ) + ) + ) + ); } catch (Exception e) { interpreter.addError( TemplateError.fromException( diff --git a/src/test/java/com/hubspot/jinjava/el/ExpressionResolverTest.java b/src/test/java/com/hubspot/jinjava/el/ExpressionResolverTest.java index 4543ee667..964000a8e 100644 --- a/src/test/java/com/hubspot/jinjava/el/ExpressionResolverTest.java +++ b/src/test/java/com/hubspot/jinjava/el/ExpressionResolverTest.java @@ -21,13 +21,7 @@ import com.hubspot.jinjava.objects.PyWrapper; import com.hubspot.jinjava.objects.date.PyishDate; import java.math.BigDecimal; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; +import java.util.*; import java.util.function.Supplier; import org.junit.Before; import org.junit.Test; @@ -664,6 +658,17 @@ public void itAddsErrorRenderingUnclosedExpression() { ); } + @Test + public void itAddsInvalidInputErrorWhenArithmeticExceptionIsThrown() { + String render = interpreter.render("{% set n = 12/0|round %}{{n}}"); + assertThat(interpreter.getErrors().get(0).getMessage()) + .contains( + "ArithmeticException when resolving expression [[ 12/0|round ]]: ArithmeticException: / by zero" + ); + assertThat(interpreter.getErrors().get(0).getReason()) + .isEqualTo(ErrorReason.INVALID_INPUT); + } + public String result(String value, TestClass testClass) { testClass.touch(); return value;