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

rpc: improve error codes for internal server errors #25678

Merged
merged 19 commits into from
Sep 9, 2022
Merged
Show file tree
Hide file tree
Changes from 11 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
4 changes: 2 additions & 2 deletions rpc/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ func TestClientErrorData(t *testing.T) {
// Check code.
if e, ok := err.(Error); !ok {
t.Fatalf("client did not return rpc.Error, got %#v", e)
} else if e.ErrorCode() != (testError{}.ErrorCode()) {
t.Fatalf("wrong error code %d, want %d", e.ErrorCode(), testError{}.ErrorCode())
} else if e.ErrorCode() != internalServerErrorCode {
t.Fatalf("wrong error code %d, want %d", e.ErrorCode(), internalServerErrorCode)
}
// Check data.
if e, ok := err.(DataError); !ok {
niczy marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
22 changes: 21 additions & 1 deletion rpc/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,14 @@ var (
_ Error = new(invalidRequestError)
_ Error = new(invalidMessageError)
_ Error = new(invalidParamsError)
_ Error = new(internalServerError)
)

const (
defaultErrorCode = -32000
internalServerErrorCode = -32603
)

const defaultErrorCode = -32000

type methodNotFoundError struct{ method string }

Expand Down Expand Up @@ -101,3 +106,18 @@ type invalidParamsError struct{ message string }
func (e *invalidParamsError) ErrorCode() int { return -32602 }

func (e *invalidParamsError) Error() string { return e.message }

type internalServerError struct{ cause error }

func (e *internalServerError) ErrorCode() int { return internalServerErrorCode }

func (e *internalServerError) Error() string {
return fmt.Sprintf("internal server error caused by %s", e.cause.Error())
}

func (e *internalServerError) ErrorData() interface{} {
if dataErr, ok := e.cause.(DataError); ok {
return dataErr.ErrorData()
}
return nil
}
5 changes: 2 additions & 3 deletions rpc/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ import (
// if err := op.wait(...); err != nil {
// h.removeRequestOp(op) // timeout, etc.
// }
//
type handler struct {
reg *serviceRegistry
unsubscribeCb *callback
Expand Down Expand Up @@ -354,7 +353,7 @@ func (h *handler) handleCall(cp *callProc, msg *jsonrpcMessage) *jsonrpcMessage
// handleSubscribe processes *_subscribe method calls.
func (h *handler) handleSubscribe(cp *callProc, msg *jsonrpcMessage) *jsonrpcMessage {
if !h.allowSubscribe {
return msg.errorResponse(ErrNotificationsUnsupported)
return msg.errorResponse(&internalServerError{cause: ErrNotificationsUnsupported})
}

// Subscription method name is first argument.
Expand Down Expand Up @@ -388,7 +387,7 @@ func (h *handler) handleSubscribe(cp *callProc, msg *jsonrpcMessage) *jsonrpcMes
func (h *handler) runMethod(ctx context.Context, msg *jsonrpcMessage, callb *callback, args []reflect.Value) *jsonrpcMessage {
result, err := callb.call(ctx, msg.Method, args)
if err != nil {
return msg.errorResponse(err)
return msg.errorResponse(&internalServerError{cause: err})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change is not correct. Here, err is the error value returned by the RPC method implementation. When the method returns an error that implements rpc.Error or rpc.DataError, we want to return the code and data contained in err.

However, with this change, the error code is overwritten.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what if the RPC method returns non rpc.Error, should we wrap it with internalServerError?

}
return msg.response(result)
}
Expand Down
3 changes: 1 addition & 2 deletions rpc/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,7 @@ func (msg *jsonrpcMessage) errorResponse(err error) *jsonrpcMessage {
func (msg *jsonrpcMessage) response(result interface{}) *jsonrpcMessage {
enc, err := json.Marshal(result)
if err != nil {
// TODO: wrap with 'internal server error'
return msg.errorResponse(err)
return msg.errorResponse(&internalServerError{cause: err})
}
return &jsonrpcMessage{Version: vsn, ID: msg.ID, Result: enc}
}
Expand Down
2 changes: 1 addition & 1 deletion rpc/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func TestServerRegisterName(t *testing.T) {
t.Fatalf("Expected service calc to be registered")
}

wantCallbacks := 10
wantCallbacks := 12
if len(svc.callbacks) != wantCallbacks {
t.Errorf("Expected %d callbacks for service 'service', got %d", wantCallbacks, len(svc.callbacks))
}
Expand Down
14 changes: 14 additions & 0 deletions rpc/testservice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,12 @@ func (testError) Error() string { return "testError" }
func (testError) ErrorCode() int { return 444 }
func (testError) ErrorData() interface{} { return "testError data" }

type MarshalErrObj struct {}

func (o *MarshalErrObj) MarshalText() ([]byte, error) {
return nil, errors.New("marshal error")
}

func (s *testService) NoArgsRets() {}

func (s *testService) Echo(str string, i int, args *echoArgs) echoResult {
Expand Down Expand Up @@ -114,6 +120,14 @@ func (s *testService) ReturnError() error {
return testError{}
}

func (s *testService) MarshalError() *MarshalErrObj {
return &MarshalErrObj{}
}

func (s *testService) Panic() string {
panic("service panic")
}

func (s *testService) CallMeBack(ctx context.Context, method string, args []interface{}) (interface{}, error) {
c, ok := ClientFromContext(ctx)
if !ok {
Expand Down
57 changes: 57 additions & 0 deletions rpc/websocket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"net/http/httptest"
"net/http/httputil"
"net/url"
"reflect"
"strings"
"sync/atomic"
"testing"
Expand Down Expand Up @@ -227,6 +228,62 @@ func TestClientWebsocketLargeMessage(t *testing.T) {
}
}

func TestClientWebsocketInternalMarshalError(t *testing.T) {
var (
srv = newTestServer()
httpsrv = httptest.NewServer(srv.WebsocketHandler(nil))
wsURL = "ws:" + strings.TrimPrefix(httpsrv.URL, "http:")
)
defer srv.Stop()
defer httpsrv.Close()

c, err := DialWebsocket(context.Background(), wsURL, "")
if err != nil {
t.Fatal(err)
}

var obj MarshalErrObj
err = c.Call(&obj, "test_marshalError")
if err == nil {
t.Fatal("test_marshalError call should return error")
}
jsonerror, ok := err.(*jsonError)
if !ok {
t.Fatalf("test_marshalError should reutrn jsonError, but %v found", reflect.TypeOf(err))
}
if jsonerror.Code != internalServerErrorCode {
t.Errorf("wrong error code %d, %d expected", jsonerror.Code, internalServerErrorCode)
}
}

func TestClientWebsocketInternalRPCPanic(t *testing.T) {
var (
srv = newTestServer()
httpsrv = httptest.NewServer(srv.WebsocketHandler(nil))
wsURL = "ws:" + strings.TrimPrefix(httpsrv.URL, "http:")
)
defer srv.Stop()
defer httpsrv.Close()

c, err := DialWebsocket(context.Background(), wsURL, "")
if err != nil {
t.Fatal(err)
}

var r string
err = c.Call(&r, "test_panic")
if err == nil {
t.Fatal("test_panic call should return error")
}
jsonerror, ok := err.(*jsonError)
if !ok {
t.Fatalf("test_panic should reutrn jsonError, but %v found", reflect.TypeOf(err))
}
if jsonerror.Code != internalServerErrorCode {
t.Errorf("wrong error code %d, %d expected", jsonerror.Code, internalServerErrorCode)
}
}

func TestClientWebsocketSevered(t *testing.T) {
t.Parallel()

Expand Down