From e75a6c4ddfc9eb7c2fab106ee6620788094fcf7d Mon Sep 17 00:00:00 2001 From: mido Date: Fri, 21 Jun 2024 06:11:29 -0700 Subject: [PATCH] Gracefully handle division by zero using ints & floats --- compiler.go | 6 ++++++ math_test.go | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/compiler.go b/compiler.go index e1167ad..cb1fab7 100644 --- a/compiler.go +++ b/compiler.go @@ -530,6 +530,9 @@ func (c *compiler) intsOperator(l int, r int, op string) (interface{}, error) { case "-": return l - r, nil case "/": + if r == 0 { + return nil, fmt.Errorf("division by zero %v %s %v", l, op, r) + } return l / r, nil case "*": return l * r, nil @@ -556,6 +559,9 @@ func (c *compiler) floatsOperator(l float64, r float64, op string) (interface{}, case "-": return l - r, nil case "/": + if r == 0 { + return nil, fmt.Errorf("division by zero %v %s %v", l, op, r) + } return l / r, nil case "*": return l * r, nil diff --git a/math_test.go b/math_test.go index a9071b3..25a8ca3 100644 --- a/math_test.go +++ b/math_test.go @@ -8,6 +8,24 @@ import ( "github.com/stretchr/testify/require" ) +func Test_Render_Int_Math_Division_By_Zero(t *testing.T) { + r := require.New(t) + input := `<%= 10 / 0 %>` + s, err := plush.Render(input, plush.NewContext()) + r.Error(err) + r.Empty(s) + r.Contains(err.Error(), "division by zero 10 / 0") +} + +func Test_Render_Int_Float_Division_By_Zero(t *testing.T) { + r := require.New(t) + input := `<%= 10.5 / 0.0 %>` + s, err := plush.Render(input, plush.NewContext()) + r.Error(err) + r.Empty(s) + r.Contains(err.Error(), "division by zero 10.5 / 0") +} + func Test_Render_Int_Math(t *testing.T) { r := require.New(t)