Skip to content

Commit

Permalink
✨ Add once warpper with error
Browse files Browse the repository at this point in the history
  • Loading branch information
tosone committed Sep 29, 2024
1 parent 7484b05 commit 38764dd
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
17 changes: 17 additions & 0 deletions pkg/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"os"
"strconv"
"strings"
"sync"

"github.com/jinzhu/copier"
"github.com/labstack/echo/v4"
Expand Down Expand Up @@ -225,3 +226,19 @@ func GetUserFromCtxForDs(c echo.Context) (*models.User, bool, error) {
}
return user, false, nil
}

// OnceWithErr ...
func OnceWithErr(once *sync.Once, fn func() error) error {
var errChan = make(chan error, 1)
defer close(errChan)
once.Do(func() {
defer func() {
if r := recover(); r != nil {
errChan <- fmt.Errorf("%v", r)
}
}()
err := fn()
errChan <- err
})
return <-errChan
}
42 changes: 42 additions & 0 deletions pkg/utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"net/http/httptest"
"reflect"
"strings"
"sync"
"testing"

"github.com/labstack/echo/v4"
Expand Down Expand Up @@ -560,3 +561,44 @@ func TestGetUserFromCtxForDs(t *testing.T) {
})
}
}

func TestOnceWithErr(t *testing.T) {
type args struct {
once *sync.Once
fn func() error
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "normal",
args: args{
once: &sync.Once{},
fn: func() error {
fmt.Println("do something")
return nil
},
},
wantErr: false,
},
{
name: "panic",
args: args{
once: &sync.Once{},
fn: func() error {
panic("panic something")
},
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := OnceWithErr(tt.args.once, tt.args.fn); (err != nil) != tt.wantErr {
t.Errorf("OnceWithErr() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}

0 comments on commit 38764dd

Please sign in to comment.