From 8dabc00a9a63a03a1a588ff1a7608dffa5e980eb Mon Sep 17 00:00:00 2001 From: Dean Sheather Date: Mon, 26 Jul 2021 20:30:31 +0000 Subject: [PATCH] Add err wrapping to dialer --- wsnet/dial.go | 15 ++++++++++++++- wsnet/error.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 wsnet/error.go diff --git a/wsnet/dial.go b/wsnet/dial.go index b1f505a0..990ed118 100644 --- a/wsnet/dial.go +++ b/wsnet/dial.go @@ -104,6 +104,17 @@ func Dial(ctx context.Context, conn net.Conn, options *DialOptions) (*Dialer, er return nil, fmt.Errorf("create peer connection: %w", err) } log.Debug(ctx, "created peer connection") + defer func() { + if err != nil { + // Wrap our error with some extra details. + err = errWrap{ + err: err, + iceServers: rtc.GetConfiguration().ICEServers, + rtc: rtc.ConnectionState(), + } + } + }() + rtc.OnConnectionStateChange(func(pcs webrtc.PeerConnectionState) { log.Debug(ctx, "connection state change", slog.F("state", pcs.String())) }) @@ -159,7 +170,9 @@ func Dial(ctx context.Context, conn net.Conn, options *DialOptions) (*Dialer, er connClosers: []io.Closer{ctrl}, } - return dialer, dialer.negotiate(ctx) + // This is on a separate line so the defer above catches it. + err = dialer.negotiate(ctx) + return dialer, err } // Dialer enables arbitrary dialing to any network and address diff --git a/wsnet/error.go b/wsnet/error.go new file mode 100644 index 00000000..aa66d548 --- /dev/null +++ b/wsnet/error.go @@ -0,0 +1,39 @@ +package wsnet + +import ( + "fmt" + "strings" + + "github.com/pion/webrtc/v3" +) + +// errWrap wraps the error with some extra details about the state of the +// connection. +type errWrap struct { + err error + + iceServers []webrtc.ICEServer + rtc webrtc.PeerConnectionState +} + +var _ error = errWrap{} +var _ interface{ Unwrap() error } = errWrap{} + +// Error implements error. +func (e errWrap) Error() string { + return fmt.Sprintf("%v (ice: [%v], rtc: %v)", e.err.Error(), e.ice(), e.rtc.String()) +} + +func (e errWrap) ice() string { + msgs := []string{} + for _, s := range e.iceServers { + msgs = append(msgs, strings.Join(s.URLs, ", ")) + } + + return strings.Join(msgs, ", ") +} + +// Unwrap implements Unwrapper. +func (e errWrap) Unwrap() error { + return e.err +}