Commit 486ede30 authored by Kirill Smelkov's avatar Kirill Smelkov

exc += Runx() - utility to run a function and translate caught exception to regular error

This might be frequently needed when running a goroutine - to catch
errors at top level and then convey they to other places as regular
errors.
parent 8f1a4ded
......@@ -177,3 +177,16 @@ func Addcallingcontext(topfunc string, e *Error) *Error {
return e
}
// run a function which raises exception, and return exception as regular error, if any.
// the error, if non-nil, will be returned with added calling context - see
// Addcallingcontext for details.
func Runx(xf func()) (err error) {
here := myname.Func()
defer Catch(func(e *Error) {
err = Addcallingcontext(here, e)
})
xf()
return
}
......@@ -146,3 +146,24 @@ func TestErrAddCallingContext(t *testing.T) {
}()
}
}
func TestRunx(t *testing.T) {
var tests = []struct { f func(); wanterr string } {
{func() {}, ""},
{do_raise11, "do_raise11: do_raise1: 1"},
}
for _, tt := range tests {
err := Runx(tt.f)
if err == nil {
if tt.wanterr != "" {
t.Errorf("runx(%v) -> nil ; want %q error", funcname(tt.f), tt.wanterr)
}
continue
}
msg := err.Error()
if msg != tt.wanterr {
t.Errorf("runx(%v) -> %q ; want %q", funcname(tt.f), msg, tt.wanterr)
}
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment