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

fix(server): send internal server errors #17

Merged
merged 5 commits into from
Jun 12, 2020
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
7 changes: 6 additions & 1 deletion client.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,12 @@ func (c *client) run() {
respCh := c.subs[msg.Id]
c.subsMu.Unlock()

respCh <- qResp{resp: msg.Payload.(*Response)}
r, ok := msg.Payload.(*Response)
if !ok {
err = msg.Payload.(*ServerError)
}

respCh <- qResp{resp: r, err: err}

if msg.Type != gql_COMPLETE {
continue
Expand Down
28 changes: 28 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,34 @@ func newTestServer(f func(*Conn)) *httptest.Server {
}))
}

func TestHandleServerError(t *testing.T) {
srv := httptest.NewServer(NewHandler(errHandler))
defer srv.Close()

conn, err := Dial(context.Background(), "ws:https://"+srv.Listener.Addr().String())
if err != nil {
t.Error(err)
return
}
defer conn.Close()

client := NewClient(conn)
_, err = client.Query(context.Background(), &Request{Query: "{ hello { world } }"})
if err == nil {
t.Log("expected an error")
t.Fail()
return
}

var serr *ServerError
if !errors.As(err, &serr) {
t.Log("wrong err type:", err)
t.Fail()
return
}
t.Log(serr)
}

func TestFailedIO(t *testing.T) {
srv := newTestServer(func(conn *Conn) {
conn.wc.CloseRead(context.Background())
Expand Down
27 changes: 22 additions & 5 deletions payload.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const (
gql_CONNECTION_KEEP_ALIVE = "connection_keep_alive"
)

// Request represents payload sent from the client.
// Request represents a payload sent from the client.
type Request struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables"`
Expand All @@ -38,13 +38,26 @@ type Response struct {
Errors []json.RawMessage `json:"errors"`
}

// Payload represents either a Client or Server payload
// ServerError represents a payload which is sent by the server if
// it encounters a non-GraphQL resolver error.
//
type ServerError struct {
Msg string `json:"msg"`
}

// Error implements the error interface.
func (e *ServerError) Error() string {
return fmt.Sprintf("internal server error: %s", e.Msg)
}

// payload represents either a Client or Server payload
type payload interface {
isPayload()
}

func (*Request) isPayload() {}
func (*Response) isPayload() {}
func (*Request) isPayload() {}
func (*Response) isPayload() {}
func (*ServerError) isPayload() {}

type unknown map[string]interface{}

Expand Down Expand Up @@ -85,10 +98,14 @@ func (m *operationMessage) UnmarshalJSON(b []byte) error {
req := new(Request)
m.Payload = req
return json.Unmarshal(raw.Payload, req)
case gql_CONNECTION_ERROR, gql_CONNECTION_ACK, gql_DATA, gql_ERROR, gql_COMPLETE, gql_CONNECTION_KEEP_ALIVE:
case gql_CONNECTION_ERROR, gql_CONNECTION_ACK, gql_DATA, gql_COMPLETE, gql_CONNECTION_KEEP_ALIVE:
resp := new(Response)
m.Payload = resp
return json.Unmarshal(raw.Payload, resp)
case gql_ERROR:
serr := new(ServerError)
m.Payload = serr
return json.Unmarshal(raw.Payload, serr)
default:
return fmt.Errorf("unsupported message type: %s", raw.Type)
}
Expand Down
12 changes: 10 additions & 2 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,10 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {

err = msg.UnmarshalJSON(b)
if err != nil {
// TODO
conn.write(ctx, operationMessage{
Type: gql_ERROR,
Payload: &ServerError{Msg: "received malformed message"},
})
continue
}

Expand All @@ -99,7 +102,12 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
func handleRequest(ctx context.Context, conn *Conn, h MessageHandler, id opId, req *Request) {
resp, err := h(ctx, req)
if err != nil {
// TODO
conn.write(ctx, operationMessage{
Id: id,
Type: gql_ERROR,
Payload: &ServerError{Msg: err.Error()},
})
return
}

msg := operationMessage{
Expand Down
136 changes: 136 additions & 0 deletions server_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package graphql_transport_ws

import (
"context"
"errors"
"net/http/httptest"
"testing"

"nhooyr.io/websocket"
)

func TestErrMessage(t *testing.T) {
srv := httptest.NewServer(NewHandler(testHandler))
defer srv.Close()

conn, err := Dial(context.Background(), "ws:https://"+srv.Listener.Addr().String())
if err != nil {
t.Error(err)
return
}
defer conn.Close()

err = conn.write(context.Background(), operationMessage{Type: gql_CONNECTION_INIT})
if err != nil {
t.Error(err)
return
}

// Should be ack message
_, err = conn.read(context.Background())
if err != nil {
t.Error(err)
return
}

err = conn.wc.Write(context.Background(), websocket.MessageBinary, []byte(`{"type":"start"`))
if err != nil {
t.Error(err)
return
}

b, err := conn.read(context.Background())
if err != nil {
t.Error(err)
return
}

msg := new(operationMessage)
err = msg.UnmarshalJSON(b)
if err != nil {
t.Error(err)
return
}

err, ok := msg.Payload.(error)
if !ok {
t.Log("expected error message from server")
t.Fail()
return
}

var serr *ServerError
if !errors.As(err, &serr) {
t.Log("wrong error type:", err)
t.Fail()
return
}
t.Log(serr)
}

func errHandler(ctx context.Context, req *Request) (*Response, error) {
return nil, errors.New("test error from message handler")
}

func TestHandlerError(t *testing.T) {
srv := httptest.NewServer(NewHandler(errHandler))
defer srv.Close()

conn, err := Dial(context.Background(), "ws:https://"+srv.Listener.Addr().String())
if err != nil {
t.Error(err)
return
}
defer conn.Close()

err = conn.write(context.Background(), operationMessage{Type: gql_CONNECTION_INIT})
if err != nil {
t.Error(err)
return
}

// Should be ack message
_, err = conn.read(context.Background())
if err != nil {
t.Error(err)
return
}

err = conn.write(context.Background(), operationMessage{
Id: "1",
Type: gql_START,
Payload: &Request{Query: "{ hello { world } }"},
})
if err != nil {
t.Error(err)
return
}

b, err := conn.read(context.Background())
if err != nil {
t.Error(err)
return
}

msg := new(operationMessage)
err = msg.UnmarshalJSON(b)
if err != nil {
t.Error(err)
return
}

err, ok := msg.Payload.(error)
if !ok {
t.Log("expected error message from server")
t.Fail()
return
}

var serr *ServerError
if !errors.As(err, &serr) {
t.Log("wrong error type:", err)
t.Fail()
return
}
t.Log(serr)
}