add TryCatch jsutil and use it in socket dialer

This commit is contained in:
syumai 2024-01-03 23:10:46 +09:00
parent 68b61bf3d5
commit cfee7c5d4e
3 changed files with 35 additions and 1 deletions

View File

@ -3,6 +3,7 @@ package sockets
import (
"context"
"net"
"syscall/js"
"time"
"github.com/syumai/workers/cloudflare/internal/cfruntimecontext"
@ -42,7 +43,12 @@ func Connect(ctx context.Context, addr string, opts *SocketOptions) (net.Conn, e
optionsObj.Set("secureTransport", string(opts.SecureTransport))
}
}
sockVal := connect.Invoke(addr, optionsObj)
sockVal, err := jsutil.TryCatch(js.FuncOf(func(_ js.Value, args []js.Value) any {
return connect.Invoke(addr, optionsObj)
}))
if err != nil {
return nil, err
}
deadline := time.Now().Add(defaultDeadline)
return newSocket(ctx, sockVal, deadline, deadline), nil
}

View File

@ -5,6 +5,18 @@ const go = new Go();
let mod;
globalThis.tryCatch = (fn) => {
try {
return {
result: fn(),
};
} catch(e) {
return {
error: e,
}
}
}
export function init(m) {
mod = m;
}

View File

@ -0,0 +1,16 @@
package jsutil
import (
"errors"
"syscall/js"
)
func TryCatch(fn js.Func) (js.Value, error) {
fnResultVal := js.Global().Call("tryCatch", fn)
resultVal := fnResultVal.Get("result")
errorVal := fnResultVal.Get("error")
if !errorVal.IsUndefined() {
return js.Value{}, errors.New(errorVal.String())
}
return resultVal, nil
}