Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add argument to WebsocketErrorFunc #2124

Merged
merged 2 commits into from
May 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 25 additions & 5 deletions graphql/handler/transport/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,24 @@ type (

var errReadTimeout = errors.New("read timeout")

var _ graphql.Transport = Websocket{}
type WebsocketError struct {
Err error

// IsReadError flags whether the error occurred on read or write to the websocket
IsReadError bool
}

func (e WebsocketError) Error() string {
if e.IsReadError {
return fmt.Sprintf("websocket read: %v", e.Err)
}
return fmt.Sprintf("websocket write: %v", e.Err)
}

var (
_ graphql.Transport = Websocket{}
_ error = WebsocketError{}
)

func (t Websocket) Supports(r *http.Request) bool {
return r.Header.Get("Upgrade") != ""
Expand Down Expand Up @@ -94,9 +111,12 @@ func (t Websocket) Do(w http.ResponseWriter, r *http.Request, exec graphql.Graph
conn.run()
}

func (c *wsConnection) handlePossibleError(err error) {
func (c *wsConnection) handlePossibleError(err error, isReadError bool) {
if c.ErrorFunc != nil && err != nil {
c.ErrorFunc(c.ctx, err)
c.ErrorFunc(c.ctx, WebsocketError{
Err: err,
IsReadError: isReadError,
})
}
}

Expand Down Expand Up @@ -181,7 +201,7 @@ func (c *wsConnection) init() bool {

func (c *wsConnection) write(msg *message) {
c.mu.Lock()
c.handlePossibleError(c.me.Send(msg))
c.handlePossibleError(c.me.Send(msg), false)
c.mu.Unlock()
}

Expand Down Expand Up @@ -227,7 +247,7 @@ func (c *wsConnection) run() {
if err != nil {
// If the connection got closed by us, don't report the error
if !errors.Is(err, net.ErrClosed) {
c.handlePossibleError(err)
c.handlePossibleError(err, true)
}
return
}
Expand Down
4 changes: 3 additions & 1 deletion graphql/handler/transport/websocket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,9 @@ func TestWebSocketErrorFunc(t *testing.T) {
h.AddTransport(transport.Websocket{
ErrorFunc: func(_ context.Context, err error) {
require.Error(t, err)
assert.Equal(t, err.Error(), "invalid message received")
assert.Equal(t, err.Error(), "websocket read: invalid message received")
assert.IsType(t, transport.WebsocketError{}, err)
assert.True(t, err.(transport.WebsocketError).IsReadError)
errFuncCalled <- true
},
})
Expand Down