feat(server): handle panic in runtime

ref #2
This commit is contained in:
2023-03-01 13:04:40 +01:00
parent fefcba5901
commit 8789b85d92
8 changed files with 41 additions and 15 deletions

View File

@ -1,15 +1,20 @@
package app
import (
"context"
"math/rand"
"sync"
"github.com/dop251/goja"
"github.com/dop251/goja_nodejs/eventloop"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/logger"
)
var ErrFuncDoesNotExist = errors.New("function does not exist")
var (
ErrFuncDoesNotExist = errors.New("function does not exist")
ErUnknownError = errors.New("unknown error")
)
type Server struct {
runtime *goja.Runtime
@ -26,16 +31,18 @@ func (s *Server) Load(name string, src string) error {
return nil
}
func (s *Server) ExecFuncByName(funcName string, args ...interface{}) (goja.Value, error) {
func (s *Server) ExecFuncByName(ctx context.Context, funcName string, args ...interface{}) (goja.Value, error) {
ctx = logger.With(ctx, logger.F("function", funcName), logger.F("args", args))
callable, ok := goja.AssertFunction(s.runtime.Get(funcName))
if !ok {
return nil, errors.WithStack(ErrFuncDoesNotExist)
}
return s.Exec(callable, args...)
return s.Exec(ctx, callable, args...)
}
func (s *Server) Exec(callable goja.Callable, args ...interface{}) (goja.Value, error) {
func (s *Server) Exec(ctx context.Context, callable goja.Callable, args ...interface{}) (goja.Value, error) {
var (
wg sync.WaitGroup
value goja.Value
@ -45,6 +52,25 @@ func (s *Server) Exec(callable goja.Callable, args ...interface{}) (goja.Value,
wg.Add(1)
s.loop.RunOnLoop(func(vm *goja.Runtime) {
logger.Debug(ctx, "executing callable")
defer wg.Done()
defer func() {
if recovered := recover(); recovered != nil {
revoveredErr, ok := recovered.(error)
if ok {
logger.Error(ctx, "recovered runtime error", logger.E(errors.WithStack(revoveredErr)))
err = errors.WithStack(ErUnknownError)
return
}
panic(recovered)
}
}()
jsArgs := make([]goja.Value, 0, len(args))
for _, a := range args {
jsArgs = append(jsArgs, vm.ToValue(a))
@ -54,8 +80,6 @@ func (s *Server) Exec(callable goja.Callable, args ...interface{}) (goja.Value,
if err != nil {
err = errors.WithStack(err)
}
wg.Done()
})
wg.Wait()