Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added panic recovery mechanism #158

Merged
merged 1 commit into from
Nov 5, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions pkg/compiler/compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,6 @@ func (c *FqlCompiler) Compile(query string) (program *runtime.Program, err error
return nil, ErrEmptyQuery
}

p := parser.New(query)
p.AddErrorListener(&errorListener{})

defer func() {
if r := recover(); r != nil {
// find out exactly what the error was and set err
Expand All @@ -78,6 +75,9 @@ func (c *FqlCompiler) Compile(query string) (program *runtime.Program, err error
}
}()

p := parser.New(query)
p.AddErrorListener(&errorListener{})

l := newVisitor(query, c.funcs)

res := p.Visit(l).(*result)
Expand Down
19 changes: 18 additions & 1 deletion pkg/runtime/program.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"github.com/MontFerret/ferret/pkg/html"
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values"
"github.com/pkg/errors"
)

type Program struct {
Expand All @@ -28,7 +29,23 @@ func (p *Program) Source() string {
return p.src
}

func (p *Program) Run(ctx context.Context, setters ...Option) ([]byte, error) {
func (p *Program) Run(ctx context.Context, setters ...Option) (result []byte, err error) {
defer func() {
if r := recover(); r != nil {
// find out exactly what the error was and set err
switch x := r.(type) {
case string:
err = errors.New(x)
case error:
err = x
default:
err = errors.New("unknown panic")
}

result = nil
}
}()

scope, closeFn := core.NewRootScope()

defer closeFn()
Expand Down
25 changes: 25 additions & 0 deletions pkg/runtime/program_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package runtime_test

import (
"context"
"github.com/MontFerret/ferret/pkg/compiler"
"github.com/MontFerret/ferret/pkg/runtime/core"
. "github.com/smartystreets/goconvey/convey"
"testing"
)

func TestProgram(t *testing.T) {
Convey("Should recover from panic", t, func() {
c := compiler.New()
c.RegisterFunction("panic", func(ctx context.Context, args ...core.Value) (core.Value, error) {
panic("test")
})

p := c.MustCompile(`RETURN PANIC()`)

_, err := p.Run(context.Background())

So(err, ShouldBeError)
So(err.Error(), ShouldEqual, "test")
})
}