better error handling

This commit is contained in:
Djeeberjr 2022-06-03 14:27:40 +02:00
parent 2be2cc0626
commit 2f5cd563ad
5 changed files with 27 additions and 3 deletions

View File

@ -73,7 +73,7 @@ func (c *Client) CreateShare(ctx context.Context, key string) (*types.Share, err
}
if !exists {
return nil, errors.New("key does not exist")
return nil, types.ErrKeyNotFound
}
err = c.db.CreateShare(ctx, share)

View File

@ -31,7 +31,7 @@ func (d *mockDB) CreateShare(ctx context.Context, share *types.Share) error {
func (d *mockDB) DeleteShare(ctx context.Context, slug string) error {
if d.shares[slug] == nil {
return errors.New("share does not exist")
return types.ErrShareNotFound
}
delete(d.shares, slug)
return nil

View File

@ -79,10 +79,20 @@ func (db *sqlDB) CreateShare(ctx context.Context, share *types.Share) error {
}
func (db *sqlDB) DeleteShare(ctx context.Context, slug string) error {
_, err := db.db.ExecContext(ctx, "DELETE FROM shares WHERE slug = ?", slug)
result, err := db.db.ExecContext(ctx, "DELETE FROM shares WHERE slug = ?", slug)
if err != nil {
return err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
return types.ErrShareNotFound
}
return nil
}

6
internal/types/errors.go Normal file
View File

@ -0,0 +1,6 @@
package types
import "errors"
var ErrKeyNotFound = errors.New("Key not found")
var ErrShareNotFound = errors.New("Share not found")

View File

@ -117,6 +117,10 @@ func CreateRouter(client *client.Client, username, password string) *mux.Router
share, err := client.CreateShare(r.Context(), shareParams.Key)
if err != nil {
if err == types.ErrKeyNotFound {
http.Error(w, "The specified key does not exist", http.StatusBadRequest)
return
}
logrus.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@ -136,6 +140,10 @@ func CreateRouter(client *client.Client, username, password string) *mux.Router
err := client.DeleteShare(r.Context(), vars["slug"])
if err != nil {
if err == types.ErrShareNotFound {
http.NotFound(w, r)
return
}
logrus.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return