Skip to content

Commit

Permalink
user codes: allow empty
Browse files Browse the repository at this point in the history
return nil if error is nil
allow an empty user message
  • Loading branch information
Greg Weber authored and gregwebs committed Jun 21, 2024
1 parent 046e551 commit 104ea06
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
12 changes: 10 additions & 2 deletions error_code_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -376,16 +376,20 @@ func TestOpErrorCode(t *testing.T) {
OpEquals(t, errcode.OpErrCode{Operation: "opcode", Err: has}, "opcode")
}

/*
func assertPanics[T any](t *testing.T, f func() T) {
t.Helper()
var res T
defer func() {
if r := recover(); r == nil {
t.Helper()
t.Errorf("testPanic: did not panic, got: %v", res)
}
}()
res = f()
}
*/

func TestUserMsg(t *testing.T) {
AssertUserMsg(t, "foo", "")
Expand All @@ -403,8 +407,12 @@ func TestUserMsg(t *testing.T) {
UserMsgEquals(t, um.AddTo(MinimalError{}), "modify")

umEmpty := errcode.UserMsg("")
assertPanics(t, func() errcode.ErrorCode { return umEmpty.AddTo(MinimalError{}) })
assertPanics(t, func() errcode.ErrorCode { return umEmpty.AddTo(nil) })
if errcode.GetUserMsg(umEmpty.AddTo(MinimalError{})) != "" {
t.Errorf("expected empty string")
}
if umEmpty.AddTo(nil) != nil {
t.Errorf("expected nil")
}

UserMsgEquals(t, ErrorWrapper{Err: ue}, "user")
UserMsgEquals(t, ErrorWrapper{Err: UserMsgErrorEmbed{EmbedUserMsg: errcode.EmbedUserMsg{Msg: "field"}}}, "field")
Expand Down
13 changes: 5 additions & 8 deletions user.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,10 @@ var _ HasUserMsg = (*UserMsgErrCode)(nil) // assert implements interface
var _ unwrapError = (*UserMsgErrCode)(nil) // assert implements interface

// AddUserMsg is constructed by UserMsg. It allows method chaining with AddTo.
type AddUserMsg func(ErrorCode) UserMsgErrCode
type AddUserMsg func(ErrorCode) UserCode

// AddTo adds the user message from UserMsg to the given ErrorCode
func (add AddUserMsg) AddTo(err ErrorCode) UserMsgErrCode {
func (add AddUserMsg) AddTo(err ErrorCode) UserCode {
return add(err)
}

Expand All @@ -109,19 +109,16 @@ func (add AddUserMsg) AddTo(err ErrorCode) UserMsgErrCode {
// return userMsg.AddTo(PathBlocked{start, end, obstacle})
// }
func UserMsg(msg string) AddUserMsg {
return func(err ErrorCode) UserMsgErrCode {
return func(err ErrorCode) UserCode {
return WithUserMsg(msg, err)
}
}

// WithUserMsg creates a UserMsgErrCode
// Panics if msg is empty or err is nil.
func WithUserMsg(msg string, err ErrorCode) UserMsgErrCode {
func WithUserMsg(msg string, err ErrorCode) UserCode {
if err == nil {
panic("WithUserMsg ErrorCode is nil")
}
if msg == "" {
panic("WithUserMsg msg is empty")
return nil
}
return UserMsgErrCode{Msg: msg, Err: err}
}

0 comments on commit 104ea06

Please sign in to comment.