Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add function Validate that creates an error when a condition is not met #221

Merged
merged 1 commit into from Oct 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Expand Up @@ -207,6 +207,7 @@ Concurrency helpers:

Error handling:

- [Validate](#validate)
- [Must](#must)
- [Try](#try)
- [TryCatch](#trycatch)
Expand Down Expand Up @@ -1933,6 +1934,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.
Expand Down
9 changes: 9 additions & 0 deletions errors.go
@@ -1,10 +1,19 @@
package lo

import (
"errors"
"fmt"
"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 {
Expand Down
13 changes: 13 additions & 0 deletions errors_test.go
Expand Up @@ -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) {
is := assert.New(t)

Expand Down