Skip to content

Commit

Permalink
code: remove the code registration hooks
Browse files Browse the repository at this point in the history
In practice any package that wants to define custom codes has to keep track of
them anyway, so that the client can coordinate with the server. The additional
hook for cosmetics in the default error string is just not worthwhile.

Updates #46.
  • Loading branch information
creachadair committed Mar 14, 2023
1 parent 2d350a3 commit 3538bb9
Show file tree
Hide file tree
Showing 2 changed files with 1 addition and 40 deletions.
16 changes: 0 additions & 16 deletions code/code.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,22 +88,6 @@ var stdError = map[Code]string{
DeadlineExceeded: "deadline exceeded",
}

// Register adds a new Code value with the specified message string. This
// function will panic if the proposed value is already registered with a
// different string.
//
// Registering a code allows you to control the string returned by the String
// method for the code value you specify. It is not necessary to register a
// code before using it. An unregistered code renders a generic string.
func Register(value int32, message string) Code {
code := Code(value)
if s, ok := stdError[code]; ok && s != message {
panic(fmt.Sprintf("code %d is already registered for %q", code, s))
}
stdError[code] = message
return code
}

// FromError returns a Code to categorize the specified error.
// If err == nil, it returns code.NoError.
// If err is (or wraps) an ErrCoder, it returns the reported code value.
Expand Down
25 changes: 1 addition & 24 deletions code/code_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,6 @@ import (
"github.com/creachadair/jrpc2/code"
)

func TestRegistration(t *testing.T) {
const message = "fun for the whole family"
c := code.Register(-100, message)
if got := c.String(); got != message {
t.Errorf("Register(-100): got %q, want %q", got, message)
} else if c != -100 {
t.Errorf("Register(-100): got %d instead", c)
}
}

func TestRegistrationError(t *testing.T) {
defer func() {
if v := recover(); v != nil {
t.Logf("Register correctly panicked: %v", v)
} else {
t.Fatalf("Register should have panicked on input %d, but did not", code.ParseError)
}
}()
code.Register(int32(code.ParseError), "bogus")
}

type testCoder code.Code

func (t testCoder) ErrCode() code.Code { return code.Code(t) }
Expand Down Expand Up @@ -91,12 +70,10 @@ func TestErr(t *testing.T) {
code code.Code
want error
}
code.Register(1, "look for the bear necessities")
code.Register(2, "the simple bear necessities")
tests := []test{
{code.NoError, nil},
{0, errors.New("error code 0")},
{1, errors.New("look for the bear necessities")},
{1, errors.New("error code 1")},
{-17, errors.New("error code -17")},
}

Expand Down

0 comments on commit 3538bb9

Please sign in to comment.