d5 / tengo

A fast script language for Go

Home Page:https://tengolang.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

UX improvement: conditionalize the installation of rescue handler...

sean- opened this issue · comments

While integrating tengo into a program, I had a simple nil pointer dereference error, but it was difficult to track down without patching tengo. I don't think it's right to change the interface of RunContext(), so I have the following proposed patch. Thoughts?

--- script.go.orig	2024-01-22 12:25:56
+++ script.go	2024-01-22 12:27:48
@@ -200,6 +200,7 @@
 	globals       []Object
 	maxAllocs     int64
 	lock          sync.RWMutex
+	disableRecover bool
 }
 
 // Run executes the compiled script in the virtual machine.
@@ -211,6 +212,12 @@
 	return v.Run()
 }
 
+// EnableRescue toggles whether or not the runtime recovery method should be
+// enabled or not (default enabled).
+func (c *Compiled) EnableRescue(b bool) {
+	c.disableRecover = !b
+}
+
 // RunContext is like Run but includes a context.
 func (c *Compiled) RunContext(ctx context.Context) (err error) {
 	c.lock.Lock()
@@ -219,6 +226,7 @@
 	v := NewVM(c.bytecode, c.globals, c.maxAllocs)
 	ch := make(chan error, 1)
 	go func() {
+		if !c.disableRecover {
 		defer func() {
 			if r := recover(); r != nil {
 				switch e := r.(type) {
@@ -231,6 +239,7 @@
 				}
 			}
 		}()
+		}
 		ch <- v.Run()
 	}()