Skip to content

Commit

Permalink
feat: 添加未找到错误处理,优化 Load 函数返回值
Browse files Browse the repository at this point in the history
  • Loading branch information
TBXark committed Dec 4, 2024
1 parent 48556dc commit 67a42cd
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion pkg/cache/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,16 @@ package cache
import (
"context"
"encoding/json"
"errors"
"fmt"
"golang.org/x/sync/singleflight"
"time"
)

var (
NotFound = fmt.Errorf("not found")
)

type Encoder interface {
Marshal(val any) ([]byte, error)
}
Expand All @@ -32,6 +38,9 @@ func Load[T any, D Decoder](ctx context.Context, c ByteCache, d D, key string) (
if err != nil {
return nil, err
}
if data == nil {
return nil, NotFound
}
var value T
err = d.Unmarshal(*data, &value)
if err != nil {
Expand Down Expand Up @@ -60,7 +69,7 @@ func LoadEx[T any, D Decoder, E Encoder](ctx context.Context, c ByteCache, d D,
}
nErr = Save[T, E](ctx, c, e, key, nObj, expiration)
if nErr != nil {
return nil, nErr
return nObj, nErr
}
return nObj, nil
})
Expand All @@ -81,3 +90,7 @@ func SaveJson[T any](ctx context.Context, c ByteCache, key string, value *T, exp
func LoadJsonEx[T any](ctx context.Context, c ByteCache, sf *singleflight.Group, key string, expiration time.Duration, builder func() (obj *T, err error)) (*T, error) {
return LoadEx[T, DecoderFunc, EncoderFunc](ctx, c, json.Unmarshal, json.Marshal, sf, key, expiration, builder)
}

func IsNotFound(err error) bool {
return errors.Is(err, NotFound)
}

0 comments on commit 67a42cd

Please sign in to comment.