From c5c7713748b05a2b113d03fcd19671ae7a89317a Mon Sep 17 00:00:00 2001 From: George MacRorie Date: Fri, 25 Nov 2022 11:51:46 +0000 Subject: [PATCH] refactor(errors): implement generic As function --- errors/errors.go | 6 ++++++ internal/storage/oplock/sql/sql.go | 9 +++------ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/errors/errors.go b/errors/errors.go index 7434e5533b..50d175418a 100644 --- a/errors/errors.go +++ b/errors/errors.go @@ -5,6 +5,12 @@ import ( "fmt" ) +// As is a utility for one-lining errors.As statements. +// e.g. cerr, match := errors.As[MyCustomError](err). +func As[E error](err error) (e E, _ bool) { + return e, errors.As(err, &e) +} + // New creates a new error with errors.New func New(s string) error { return errors.New(s) diff --git a/internal/storage/oplock/sql/sql.go b/internal/storage/oplock/sql/sql.go index 93ce1e0c19..b03fde7d84 100644 --- a/internal/storage/oplock/sql/sql.go +++ b/internal/storage/oplock/sql/sql.go @@ -2,12 +2,11 @@ package memory import ( "context" - "errors" "fmt" "time" sq "github.com/Masterminds/squirrel" - flipterrors "go.flipt.io/flipt/errors" + "go.flipt.io/flipt/errors" "go.flipt.io/flipt/internal/storage/oplock" storagesql "go.flipt.io/flipt/internal/storage/sql" "go.uber.org/zap" @@ -37,13 +36,11 @@ func New(logger *zap.Logger, driver storagesql.Driver, builder sq.StatementBuild func (s *Service) TryAcquire(ctx context.Context, operation oplock.Operation, duration time.Duration) (acquired bool, entry oplock.LockEntry, err error) { entry, err = s.readEntry(ctx, operation) if err != nil { - var errnf flipterrors.ErrNotFound - if errors.As(err, &errnf) { + if _, match := errors.As[errors.ErrNotFound](err); match { // entry does not exist so we try and create one entry, err := s.insertEntry(ctx, operation, duration) if err != nil { - var errinvalid flipterrors.ErrInvalid - if errors.As(err, &errinvalid) { + if _, match := errors.As[errors.ErrInvalid](err); match { // check if the entry is invalid due to // uniqueness constraint violation // if so re-read the current entry and return that