Skip to content

Commit

Permalink
Add better errors for nil dereference
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Aug 20, 2018
1 parent c67292b commit f1ff6e1
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
3 changes: 3 additions & 0 deletions eval.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,9 @@ func (n propertyNode) Eval(env interface{}) (interface{}, error) {
}
p, ok := extract(v, n.property)
if !ok {
if isNil(v) {
return nil, fmt.Errorf("%v is nil", n.node)
}
return nil, fmt.Errorf("%v undefined (type %T has no field %v)", n, v, n.property)
}
return p, nil
Expand Down
15 changes: 15 additions & 0 deletions eval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,21 @@ var evalErrorTests = []evalErrorTest{
nil,
"too many arguments: len(a, b)",
},
{
"Foo.Map",
struct{ Foo map[string]int }{Foo: nil},
"Foo is nil",
},
{
"Foo.Bar",
struct{ Foo *struct{ Bar bool } }{Foo: nil},
"Foo is nil",
},
{
"Foo.Panic",
struct{ Foo interface{} }{Foo: nil},
"Foo is nil",
},
}

func TestEval(t *testing.T) {
Expand Down
5 changes: 5 additions & 0 deletions runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,8 @@ func contains(needle interface{}, array interface{}) (bool, error) {
}
return false, nil
}

func isNil(val interface{}) bool {
v := reflect.ValueOf(val)
return !v.IsValid() || v.IsNil()
}

0 comments on commit f1ff6e1

Please sign in to comment.