Skip to content

Commit

Permalink
feat(misc/must): add NotNilWrap to assert value is not nil otherwise …
Browse files Browse the repository at this point in the history
…output wrapped panic info
  • Loading branch information
saitofun committed May 30, 2024
1 parent 62e17b5 commit 6f3429d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
7 changes: 7 additions & 0 deletions misc/must/must.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,10 @@ func NotNilV[V any](v V) V {
}
return v
}

func NotNilWrap(v any, msg string, args ...any) {
rv := reflectx.Indirect(v)
if rv == reflectx.InvalidValue {
panic(errors.Errorf("must not nil, but got invalid value "+msg, args...))
}
}
20 changes: 20 additions & 0 deletions misc/must/must_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,23 @@ func ExampleNotNilV() {
// 1
// must not nil: invalid value
}

func ExampleNotNilWrap() {
func() {
defer func() {
fmt.Println(recover())
}()
must.NotNilWrap((*int)(nil), "invalid business data1")
}()

func() {
defer func() {
fmt.Println(recover())
}()
must.NotNilWrap(any((*int)(nil)), "invalid business data2")
}()

// Output:
// must not nil, but got invalid value invalid business data1
// must not nil, but got invalid value invalid business data2
}

0 comments on commit 6f3429d

Please sign in to comment.