Skip to content

Commit 610cf02

Browse files
niczyNicholas Zhaofjl
authored
rpc: improve error codes for internal server errors (#25678)
This changes the error code returned by the RPC server in certain situations: - handler panic: code -32603 - result marshaling error: code -32603 - attempt to subscribe via HTTP: code -32001 In all of the above cases, the server previously returned the default error code -32000. Co-authored-by: Nicholas Zhao <[email protected]> Co-authored-by: Felix Lange <[email protected]>
1 parent 06151eb commit 610cf02

File tree

8 files changed

+52
-11
lines changed

8 files changed

+52
-11
lines changed

rpc/client_test.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,11 +82,15 @@ func TestClientErrorData(t *testing.T) {
8282
}
8383

8484
// Check code.
85+
// The method handler returns an error value which implements the rpc.Error
86+
// interface, i.e. it has a custom error code. The server returns this error code.
87+
expectedCode := testError{}.ErrorCode()
8588
if e, ok := err.(Error); !ok {
8689
t.Fatalf("client did not return rpc.Error, got %#v", e)
87-
} else if e.ErrorCode() != (testError{}.ErrorCode()) {
88-
t.Fatalf("wrong error code %d, want %d", e.ErrorCode(), testError{}.ErrorCode())
90+
} else if e.ErrorCode() != expectedCode {
91+
t.Fatalf("wrong error code %d, want %d", e.ErrorCode(), expectedCode)
8992
}
93+
9094
// Check data.
9195
if e, ok := err.(DataError); !ok {
9296
t.Fatalf("client did not return rpc.DataError, got %#v", e)

rpc/errors.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,15 @@ var (
5454
_ Error = new(invalidRequestError)
5555
_ Error = new(invalidMessageError)
5656
_ Error = new(invalidParamsError)
57+
_ Error = new(internalServerError)
5758
)
5859

59-
const defaultErrorCode = -32000
60+
const (
61+
errcodeDefault = -32000
62+
errcodeNotificationsUnsupported = -32001
63+
errcodePanic = -32603
64+
errcodeMarshalError = -32603
65+
)
6066

6167
type methodNotFoundError struct{ method string }
6268

@@ -101,3 +107,13 @@ type invalidParamsError struct{ message string }
101107
func (e *invalidParamsError) ErrorCode() int { return -32602 }
102108

103109
func (e *invalidParamsError) Error() string { return e.message }
110+
111+
// internalServerError is used for server errors during request processing.
112+
type internalServerError struct {
113+
code int
114+
message string
115+
}
116+
117+
func (e *internalServerError) ErrorCode() int { return e.code }
118+
119+
func (e *internalServerError) Error() string { return e.message }

rpc/handler.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,6 @@ import (
4848
// if err := op.wait(...); err != nil {
4949
// h.removeRequestOp(op) // timeout, etc.
5050
// }
51-
//
5251
type handler struct {
5352
reg *serviceRegistry
5453
unsubscribeCb *callback
@@ -354,7 +353,10 @@ func (h *handler) handleCall(cp *callProc, msg *jsonrpcMessage) *jsonrpcMessage
354353
// handleSubscribe processes *_subscribe method calls.
355354
func (h *handler) handleSubscribe(cp *callProc, msg *jsonrpcMessage) *jsonrpcMessage {
356355
if !h.allowSubscribe {
357-
return msg.errorResponse(ErrNotificationsUnsupported)
356+
return msg.errorResponse(&internalServerError{
357+
code: errcodeNotificationsUnsupported,
358+
message: ErrNotificationsUnsupported.Error(),
359+
})
358360
}
359361

360362
// Subscription method name is first argument.

rpc/json.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,15 +104,14 @@ func (msg *jsonrpcMessage) errorResponse(err error) *jsonrpcMessage {
104104
func (msg *jsonrpcMessage) response(result interface{}) *jsonrpcMessage {
105105
enc, err := json.Marshal(result)
106106
if err != nil {
107-
// TODO: wrap with 'internal server error'
108-
return msg.errorResponse(err)
107+
return msg.errorResponse(&internalServerError{errcodeMarshalError, err.Error()})
109108
}
110109
return &jsonrpcMessage{Version: vsn, ID: msg.ID, Result: enc}
111110
}
112111

113112
func errorMessage(err error) *jsonrpcMessage {
114113
msg := &jsonrpcMessage{Version: vsn, ID: null, Error: &jsonError{
115-
Code: defaultErrorCode,
114+
Code: errcodeDefault,
116115
Message: err.Error(),
117116
}}
118117
ec, ok := err.(Error)

rpc/server_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ func TestServerRegisterName(t *testing.T) {
4545
t.Fatalf("Expected service calc to be registered")
4646
}
4747

48-
wantCallbacks := 10
48+
wantCallbacks := 12
4949
if len(svc.callbacks) != wantCallbacks {
5050
t.Errorf("Expected %d callbacks for service 'service', got %d", wantCallbacks, len(svc.callbacks))
5151
}

rpc/service.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ package rpc
1818

1919
import (
2020
"context"
21-
"errors"
2221
"fmt"
2322
"reflect"
2423
"runtime"
@@ -199,7 +198,7 @@ func (c *callback) call(ctx context.Context, method string, args []reflect.Value
199198
buf := make([]byte, size)
200199
buf = buf[:runtime.Stack(buf, false)]
201200
log.Error("RPC method " + method + " crashed: " + fmt.Sprintf("%v\n%s", err, buf))
202-
errRes = errors.New("method handler crashed")
201+
errRes = &internalServerError{errcodePanic, "method handler crashed"}
203202
}
204203
}()
205204
// Run the callback.

rpc/testdata/internal-error.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// These tests trigger various 'internal error' conditions.
2+
3+
--> {"jsonrpc":"2.0","id":1,"method":"test_marshalError","params": []}
4+
<-- {"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"json: error calling MarshalText for type *rpc.MarshalErrObj: marshal error"}}
5+
6+
--> {"jsonrpc":"2.0","id":2,"method":"test_panic","params": []}
7+
<-- {"jsonrpc":"2.0","id":2,"error":{"code":-32603,"message":"method handler crashed"}}

rpc/testservice_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,12 @@ func (testError) Error() string { return "testError" }
7070
func (testError) ErrorCode() int { return 444 }
7171
func (testError) ErrorData() interface{} { return "testError data" }
7272

73+
type MarshalErrObj struct{}
74+
75+
func (o *MarshalErrObj) MarshalText() ([]byte, error) {
76+
return nil, errors.New("marshal error")
77+
}
78+
7379
func (s *testService) NoArgsRets() {}
7480

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

123+
func (s *testService) MarshalError() *MarshalErrObj {
124+
return &MarshalErrObj{}
125+
}
126+
127+
func (s *testService) Panic() string {
128+
panic("service panic")
129+
}
130+
117131
func (s *testService) CallMeBack(ctx context.Context, method string, args []interface{}) (interface{}, error) {
118132
c, ok := ClientFromContext(ctx)
119133
if !ok {

0 commit comments

Comments
 (0)