Skip to content

Commit e10a35d

Browse files
authored
Add Wrap and Unwrap method to hold self error (#352)
1 parent df2cccd commit e10a35d

File tree

4 files changed

+19
-1
lines changed

4 files changed

+19
-1
lines changed

expr_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -1348,7 +1348,7 @@ func TestCompile_exposed_error(t *testing.T) {
13481348

13491349
b, err := json.Marshal(err)
13501350
require.NoError(t, err)
1351-
require.Equal(t, `{"Line":1,"Column":2,"Message":"invalid operation: == (mismatched types int and bool)","Snippet":"\n | 1 == true\n | ..^"}`, string(b))
1351+
require.Equal(t, `{"Line":1,"Column":2,"Message":"invalid operation: == (mismatched types int and bool)","Snippet":"\n | 1 == true\n | ..^","Prev":null}`, string(b))
13521352
}
13531353

13541354
func TestCompile_deref(t *testing.T) {

file/error.go

+11
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ type Error struct {
1010
Location
1111
Message string
1212
Snippet string
13+
Prev error
1314
}
1415

1516
func (e *Error) Error() string {
@@ -44,6 +45,16 @@ func (e *Error) Bind(source *Source) *Error {
4445
return e
4546
}
4647

48+
49+
func (e *Error) Unwrap() error {
50+
return e.Prev
51+
}
52+
53+
func (e *Error) Wrap(err error) {
54+
e.Prev = err
55+
}
56+
57+
4758
func (e *Error) format() string {
4859
if e.Location.Empty() {
4960
return e.Message

vm/vm.go

+3
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ func (vm *VM) Run(program *Program, env interface{}) (_ interface{}, err error)
6161
Location: program.Locations[vm.ip-1],
6262
Message: fmt.Sprintf("%v", r),
6363
}
64+
if err, ok := r.(error); ok {
65+
f.Wrap(err)
66+
}
6467
err = f.Bind(program.Source)
6568
}
6669
}()

vm/vm_test.go

+4
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,10 @@ func TestRun_MethodWithError(t *testing.T) {
274274
out, err := vm.Run(program, env)
275275
require.EqualError(t, err, "error (1:1)\n | WillError(\"yes\")\n | ^")
276276
require.Equal(t, nil, out)
277+
278+
selfErr := errors.Unwrap(err)
279+
require.NotNil(t, err)
280+
require.Equal(t, "error", selfErr.Error())
277281
}
278282

279283
func TestRun_FastMethods(t *testing.T) {

0 commit comments

Comments
 (0)