Skip to content

Commit f1ff6e1

Browse files
committed
Add better errors for nil dereference
1 parent c67292b commit f1ff6e1

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

eval.go

+3
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,9 @@ func (n propertyNode) Eval(env interface{}) (interface{}, error) {
238238
}
239239
p, ok := extract(v, n.property)
240240
if !ok {
241+
if isNil(v) {
242+
return nil, fmt.Errorf("%v is nil", n.node)
243+
}
241244
return nil, fmt.Errorf("%v undefined (type %T has no field %v)", n, v, n.property)
242245
}
243246
return p, nil

eval_test.go

+15
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,21 @@ var evalErrorTests = []evalErrorTest{
447447
nil,
448448
"too many arguments: len(a, b)",
449449
},
450+
{
451+
"Foo.Map",
452+
struct{ Foo map[string]int }{Foo: nil},
453+
"Foo is nil",
454+
},
455+
{
456+
"Foo.Bar",
457+
struct{ Foo *struct{ Bar bool } }{Foo: nil},
458+
"Foo is nil",
459+
},
460+
{
461+
"Foo.Panic",
462+
struct{ Foo interface{} }{Foo: nil},
463+
"Foo is nil",
464+
},
450465
}
451466

452467
func TestEval(t *testing.T) {

runtime.go

+5
Original file line numberDiff line numberDiff line change
@@ -120,3 +120,8 @@ func contains(needle interface{}, array interface{}) (bool, error) {
120120
}
121121
return false, nil
122122
}
123+
124+
func isNil(val interface{}) bool {
125+
v := reflect.ValueOf(val)
126+
return !v.IsValid() || v.IsNil()
127+
}

0 commit comments

Comments
 (0)