Skip to content

Commit

Permalink
refactor(errors): implement generic As function
Browse files Browse the repository at this point in the history
  • Loading branch information
GeorgeMac committed Nov 25, 2022
1 parent 8d3cdb2 commit c5c7713
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
6 changes: 6 additions & 0 deletions errors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 3 additions & 6 deletions internal/storage/oplock/sql/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit c5c7713

Please sign in to comment.