Cookies management by TermsFeed Cookie Consent

Repository errors

9/21

Add the error definitions to the website/repository.go file and let’s analyze them:

  • An ErrDuplicate error means that the user is trying to add a record that already exists, i.e., with the same name, because in our repository, we assume that each website should have a unique name. This error should be returned from the methods that write to the database - Create() or Update() when a violation of the uniqueness constraint is detected.
  • An error ErrNotExist means no record with the specified parameters in the database. This should be returned from any functions that pull a single object from the repository. In our case, this is the GetByName() method.
  • An ErrUpdateFailed error is an error returned by the Update() method. It should appear when no row has been affected by the requested update, such as when the change was to a row with a non-existent id.
  • An ErrDeleteFailed error should occur when no row was deleted as a result of executing the Delete() method, e.g., because there is no row with the given id.

Of course, when using the repository, a whole bunch of other errors can also occur, e.g., network errors, connection failures, timeouts, etc. However, these are unexpected errors, and not every application needs to handle them in a special way. But user errors like the above should always be handled so that the user can react and correct bad input.

website/repository.go

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
package website

import (
    "context"
    "errors"
)

var (
    ErrDuplicate    = errors.New("record already exists")
    ErrNotExist    = errors.New("row does not exist")
    ErrUpdateFailed = errors.New("update failed")
    ErrDeleteFailed = errors.New("delete failed")
)

type Repository interface {
    Migrate(ctx context.Context) error
    Create(ctx context.Context, website Website) (*Website, error)
    All(ctx context.Context) ([]Website, error)
    GetByName(ctx context.Context, name string) (*Website, error)
    Update(ctx context.Context, id int64, updated Website) (*Website, error)
    Delete(ctx context.Context, id int64) error
}
9/21