Add Wrap and Unwrap method to hold self error (#352)

This commit is contained in:
hesining
2023-03-10 21:08:40 +01:00
committed by GitHub
parent 4876b330e5
commit 9255e223d9
4 changed files with 19 additions and 1 deletions
+1 -1
View File
@@ -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) {
+11
View File
@@ -10,6 +10,7 @@ type Error struct {
Location
Message string
Snippet string
Prev error
}
func (e *Error) Error() string {
@@ -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
+3
View File
@@ -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)
}
}()
+4
View File
@@ -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) {