Skip to content

Commit

Permalink
rpc: redefine ErrNotificationsUnsupported with error code -32601
Browse files Browse the repository at this point in the history
  • Loading branch information
fjl committed Dec 8, 2022
1 parent de0d500 commit 2301ca7
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 6 deletions.
25 changes: 24 additions & 1 deletion rpc/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ var (

const (
errcodeDefault = -32000
errcodeNotificationsUnsupported = -32001
errcodeTimeout = -32002
errcodePanic = -32603
errcodeMarshalError = -32603
Expand All @@ -77,6 +76,30 @@ func (e *methodNotFoundError) Error() string {
return fmt.Sprintf("the method %s does not exist/is not available", e.method)
}

type notificationsUnsupportedError struct{}

func (e notificationsUnsupportedError) Error() string {
return "notifications not supported"
}

func (e notificationsUnsupportedError) ErrorCode() int { return -32601 }

// Is checks for equivalence to another error. Here we define that all errors with code
// -32601 (method not found) are equivalent to notificationsUnsupportedError. This is
// done to enable the following pattern:
//
// sub, err := client.Subscribe(...)
// if errors.Is(err, rpc.ErrNotificationsUnsupported) {
// // server doesn't support subscriptions
// }
func (e notificationsUnsupportedError) Is(other error) bool {
if other == (notificationsUnsupportedError{}) {
return true
}
rpcErr, ok := other.(Error)
return ok && rpcErr.ErrorCode() == -32601
}

type subscriptionNotFoundError struct{ namespace, subscription string }

func (e *subscriptionNotFoundError) ErrorCode() int { return -32601 }
Expand Down
5 changes: 1 addition & 4 deletions rpc/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -475,10 +475,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(&internalServerError{
code: errcodeNotificationsUnsupported,
message: ErrNotificationsUnsupported.Error(),
})
return msg.errorResponse(ErrNotificationsUnsupported)
}

// Subscription method name is first argument.
Expand Down
3 changes: 2 additions & 1 deletion rpc/subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ import (

var (
// ErrNotificationsUnsupported is returned when the connection doesn't support notifications
ErrNotificationsUnsupported = errors.New("notifications not supported")
ErrNotificationsUnsupported = notificationsUnsupportedError{}

// ErrSubscriptionNotFound is returned when the notification for the given id is not found
ErrSubscriptionNotFound = errors.New("subscription not found")
)
Expand Down

0 comments on commit 2301ca7

Please sign in to comment.