mirror of
https://github.com/samber/lo.git
synced 2026-04-22 23:47:11 +08:00
Add function Validate that creates an error when a condition is not met (#221)
This commit is contained in:
@@ -208,6 +208,7 @@ Concurrency helpers:
|
||||
|
||||
Error handling:
|
||||
|
||||
- [Validate](#validate)
|
||||
- [Must](#must)
|
||||
- [Try](#try)
|
||||
- [Try1 -> Try6](#try0-6)
|
||||
@@ -2079,6 +2080,21 @@ ch := lo.Async2(func() (int, string) {
|
||||
// chan lo.Tuple2[int, string] ({42, "Hello"})
|
||||
```
|
||||
|
||||
### Validate
|
||||
|
||||
Helper function that creates an error when a condition is not met.
|
||||
|
||||
```go
|
||||
slice := []string{"a"}
|
||||
val := lo.Validate(len(slice) == 0, "Slice should be empty but contains %v", slice)
|
||||
// error("Slice should be empty but contains [a]")
|
||||
|
||||
slice := []string{}
|
||||
val := lo.Validate(len(slice) == 0, "Slice should be empty but contains %v", slice)
|
||||
// nil
|
||||
```
|
||||
|
||||
|
||||
### Must
|
||||
|
||||
Wraps a function call to panics if second argument is `error` or `false`, returns the value otherwise.
|
||||
|
||||
@@ -6,6 +6,14 @@ import (
|
||||
"reflect"
|
||||
)
|
||||
|
||||
// Validate is a helper that creates an error when a condition is not met.
|
||||
func Validate(ok bool, format string, args ...any) error {
|
||||
if !ok {
|
||||
return errors.New(fmt.Sprint(format, args))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
|
||||
if len(msgAndArgs) == 1 {
|
||||
if msgAsStr, ok := msgAndArgs[0].(string); ok {
|
||||
|
||||
@@ -8,6 +8,19 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
is := assert.New(t)
|
||||
|
||||
slice := []string{"a"}
|
||||
result1 := Validate(len(slice) == 0, "Slice should be empty but contains %v", slice)
|
||||
|
||||
slice = []string{}
|
||||
result2 := Validate(len(slice) == 0, "Slice should be empty but contains %v", slice)
|
||||
|
||||
is.Error(result1)
|
||||
is.NoError(result2)
|
||||
}
|
||||
|
||||
func TestMust(t *testing.T) {
|
||||
t.Parallel()
|
||||
is := assert.New(t)
|
||||
|
||||
Reference in New Issue
Block a user