From a64919945bdb65202783c5f9e078c3e735efc58f Mon Sep 17 00:00:00 2001 From: Johan Brandhorst-Satzkorn Date: Fri, 27 Jan 2023 22:53:25 -0800 Subject: [PATCH] net/http: improve js fetch errors The Error type used in failed fetch invocations contain more information than we're currently extracting. Optimistically look for the cause field for extra context for errors. Change-Id: I6c8e4b230a21ec684af2107707aa605fc2148fcf Reviewed-on: https://go-review.googlesource.com/c/go/+/463978 TryBot-Result: Gopher Robot Reviewed-by: Dmitri Shuralyov Reviewed-by: David Chase Reviewed-by: Evan Phoenix Run-TryBot: Johan Brandhorst-Satzkorn Reviewed-by: Dmitri Shuralyov Auto-Submit: Johan Brandhorst-Satzkorn --- src/net/http/roundtrip_js.go | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/net/http/roundtrip_js.go b/src/net/http/roundtrip_js.go index 21d8df9686..4f381247cd 100644 --- a/src/net/http/roundtrip_js.go +++ b/src/net/http/roundtrip_js.go @@ -191,7 +191,22 @@ func (t *Transport) RoundTrip(req *Request) (*Response, error) { failure = js.FuncOf(func(this js.Value, args []js.Value) any { success.Release() failure.Release() - errCh <- fmt.Errorf("net/http: fetch() failed: %s", args[0].Get("message").String()) + err := args[0] + // The error is a JS Error type + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error + // We can use the toString() method to get a string representation of the error. + errMsg := err.Call("toString").String() + // Errors can optionally contain a cause. + if cause := err.Get("cause"); !cause.IsUndefined() { + // The exact type of the cause is not defined, + // but if it's another error, we can call toString() on it too. + if !cause.Get("toString").IsUndefined() { + errMsg += ": " + cause.Call("toString").String() + } else if cause.Type() == js.TypeString { + errMsg += ": " + cause.String() + } + } + errCh <- fmt.Errorf("net/http: fetch() failed: %s", errMsg) return nil })