Skip to content

Commit

Permalink
feat: adding ErrorsAs
Browse files Browse the repository at this point in the history
  • Loading branch information
samber committed Oct 2, 2022
1 parent 31f3bc3 commit edda239
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 0 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,12 @@

@samber: I sometimes forget to update this file. Ping me on [Twitter](https://twitter.com/samuelberthe) or open an issue in case of error. We need to keep a clear changelog for easier lib upgrade.

## 1.29.0 (2022-10-02)

Adding:

- lo.ErrorAs

## 1.28.0 (2022-09-05)

Adding:
Expand Down
24 changes: 24 additions & 0 deletions README.md
Expand Up @@ -212,6 +212,7 @@ Error handling:
- [TryCatch](#trycatch)
- [TryWithErrorValue](#trywitherrorvalue)
- [TryCatchWithErrorValue](#trycatchwitherrorvalue)
- [ErrorsAs](#errorsas)

Constraints:

Expand Down Expand Up @@ -2071,6 +2072,29 @@ ok := lo.TryCatchWithErrorValue(func() error {
// caught == true
```

### ErrorsAs

A shortcut for:

```go
err := doSomething()

var rateLimitErr *RateLimitError
if ok := errors.As(err, &rateLimitErr); ok {
// retry later
}
```

1 line `lo` helper:

```go
err := doSomething()

if rateLimitErr, ok := lo.ErrorsAs[*RateLimitError](err); ok {
// retry later
}
```

## 馃洨 Benchmark

We executed a simple benchmark with the a dead-simple `lo.Map` loop:
Expand Down
8 changes: 8 additions & 0 deletions errors.go
@@ -1,6 +1,7 @@
package lo

import (
"errors"
"fmt"
"reflect"
)
Expand Down Expand Up @@ -199,3 +200,10 @@ func TryCatchWithErrorValue(callback func() error, catch func(any)) {
catch(err)
}
}

// ErrorsAs is a shortcut for errors.As(err, &&T).
func ErrorsAs[T error](err error) (T, bool) {
var t T
ok := errors.As(err, &t)
return t, ok
}
24 changes: 24 additions & 0 deletions errors_test.go
Expand Up @@ -361,3 +361,27 @@ func TestTryCatchWithErrorValue(t *testing.T) {
})
is.False(caught)
}

type internalError struct {
foobar string
}

func (e *internalError) Error() string {
return fmt.Sprintf("internal error")
}

func TestErrorsAs(t *testing.T) {
is := assert.New(t)

err, ok := ErrorsAs[*internalError](fmt.Errorf("hello world"))
is.False(ok)
is.Nil(nil, err)

err, ok = ErrorsAs[*internalError](&internalError{foobar: "foobar"})
is.True(ok)
is.Equal(&internalError{foobar: "foobar"}, err)

err, ok = ErrorsAs[*internalError](nil)
is.False(ok)
is.Nil(nil, err)
}

0 comments on commit edda239

Please sign in to comment.