Skip to content

Commit

Permalink
Add Wrap and Unwrap method to hold self error (#352)
Browse files Browse the repository at this point in the history
  • Loading branch information
hesining committed Mar 10, 2023
1 parent df2cccd commit e10a35d
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion expr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1348,7 +1348,7 @@ func TestCompile_exposed_error(t *testing.T) {

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

func TestCompile_deref(t *testing.T) {
Expand Down
11 changes: 11 additions & 0 deletions file/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ type Error struct {
Location
Message string
Snippet string
Prev error
}

func (e *Error) Error() string {
Expand Down Expand Up @@ -44,6 +45,16 @@ func (e *Error) Bind(source *Source) *Error {
return e
}


func (e *Error) Unwrap() error {
return e.Prev
}

func (e *Error) Wrap(err error) {
e.Prev = err
}


func (e *Error) format() string {
if e.Location.Empty() {
return e.Message
Expand Down
3 changes: 3 additions & 0 deletions vm/vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ func (vm *VM) Run(program *Program, env interface{}) (_ interface{}, err error)
Location: program.Locations[vm.ip-1],
Message: fmt.Sprintf("%v", r),
}
if err, ok := r.(error); ok {
f.Wrap(err)
}
err = f.Bind(program.Source)
}
}()
Expand Down
4 changes: 4 additions & 0 deletions vm/vm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,10 @@ func TestRun_MethodWithError(t *testing.T) {
out, err := vm.Run(program, env)
require.EqualError(t, err, "error (1:1)\n | WillError(\"yes\")\n | ^")
require.Equal(t, nil, out)

selfErr := errors.Unwrap(err)
require.NotNil(t, err)
require.Equal(t, "error", selfErr.Error())
}

func TestRun_FastMethods(t *testing.T) {
Expand Down

0 comments on commit e10a35d

Please sign in to comment.