Skip to content

Commit

Permalink
minor: improve error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
jpts committed Sep 24, 2022
1 parent a440c31 commit 9997fc2
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
29 changes: 19 additions & 10 deletions cmd/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package cmd
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
Expand All @@ -15,6 +15,7 @@ import (

"github.com/gorilla/websocket"
"github.com/moby/term"
"github.com/pkg/errors"
"k8s.io/klog/v2"
)

Expand Down Expand Up @@ -48,15 +49,23 @@ func (d *WebsocketRoundTripper) RoundTrip(r *http.Request) (*http.Response, erro
conn, resp, err := d.Dialer.Dial(r.URL.String(), r.Header)
if e, ok := err.(*net.OpError); ok {
return nil, fmt.Errorf("Error connecting to %s, %s", e.Addr, e.Err)
} else if err != nil {
return nil, err
} else if resp.StatusCode != 101 {
var msg ApiServerError
err := json.NewDecoder(resp.Body).Decode(&msg)
if err != nil {
return nil, errors.New("Error from server, unable to decode response")
} else if err != nil || resp.StatusCode != 101 {
if resp.Header.Get("Content-Type") == "application/json" {
var msg ApiServerError
jerr := json.NewDecoder(resp.Body).Decode(&msg)
if jerr != nil {
return nil, errors.Wrap(err, "Error from server, unable to decode response")
}
return nil, fmt.Errorf("Error from server (%s): %s", msg.Reason, msg.Message)
} else {
body, ioerr := ioutil.ReadAll(resp.Body)
if ioerr != nil {
return nil, errors.Wrap(err, "Server Error, unabled to decode body")
}
resp.Body.Close()

return nil, fmt.Errorf("Error from server: %s", body)
}
return nil, fmt.Errorf("Error from server (%s): %s", msg.Reason, msg.Message)
}
defer conn.Close()
return resp, d.Callback(d, conn)
Expand Down Expand Up @@ -118,7 +127,7 @@ func (d *WebsocketRoundTripper) WsCallback(ws *websocket.Conn) error {
case streamErr:
w = os.Stderr
default:
errChan <- errors.New("Unknown stream type")
errChan <- fmt.Errorf("Unknown stream type: %d", buf[0])
continue
}

Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ require (
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/net v0.0.0-20220722155237-a158d28d115b // indirect
golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8 // indirect
Expand Down

0 comments on commit 9997fc2

Please sign in to comment.