Fix error comparisons

This commit is contained in:
Deluan 2022-09-30 18:54:25 -04:00
parent 7b0a8f47de
commit db67c1277e
27 changed files with 93 additions and 73 deletions

View File

@ -4,6 +4,7 @@ import (
"bytes"
"context"
_ "embed"
"errors"
"net/http"
"time"
@ -67,7 +68,7 @@ func (s *Router) getLinkStatus(w http.ResponseWriter, r *http.Request) {
resp := map[string]interface{}{}
u, _ := request.UserFrom(r.Context())
key, err := s.sessionKeys.Get(r.Context(), u.ID)
if err != nil && err != model.ErrNotFound {
if err != nil && !errors.Is(err, model.ErrNotFound) {
resp["error"] = err
resp["status"] = false
_ = rest.RespondWithJSON(w, http.StatusInternalServerError, resp)

View File

@ -3,6 +3,7 @@ package listenbrainz
import (
"context"
"encoding/json"
"errors"
"net/http"
"github.com/deluan/rest"
@ -62,7 +63,7 @@ func (s *Router) getLinkStatus(w http.ResponseWriter, r *http.Request) {
resp := map[string]interface{}{}
u, _ := request.UserFrom(r.Context())
key, err := s.sessionKeys.Get(r.Context(), u.ID)
if err != nil && err != model.ErrNotFound {
if err != nil && !errors.Is(err, model.ErrNotFound) {
resp["error"] = err
resp["status"] = false
_ = rest.RespondWithJSON(w, http.StatusInternalServerError, resp)

View File

@ -2,6 +2,7 @@ package spotify
import (
"context"
"errors"
"fmt"
"net/http"
"sort"
@ -46,7 +47,7 @@ func (s *spotifyAgent) AgentName() string {
func (s *spotifyAgent) GetImages(ctx context.Context, id, name, mbid string) ([]agents.ArtistImage, error) {
a, err := s.searchArtist(ctx, name)
if err != nil {
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
log.Warn(ctx, "Artist not found in Spotify", "artist", name)
} else {
log.Error(ctx, "Error calling Spotify", "artist", name, err)

View File

@ -57,7 +57,7 @@ func (ci *imageInfo) Key() string {
func (a *artwork) Get(ctx context.Context, id string, size int) (io.ReadCloser, error) {
path, lastUpdate, err := a.getImagePath(ctx, id)
if err != nil && err != model.ErrNotFound {
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, err
}
@ -106,7 +106,7 @@ func (a *artwork) getImagePath(ctx context.Context, id string) (path string, las
mf, err = a.ds.MediaFile(ctx).Get(id)
// If it is not, may be an albumId
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return a.getImagePath(ctx, "al-"+id)
}
if err != nil {

View File

@ -5,6 +5,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
@ -146,7 +147,7 @@ func (s *playlists) updatePlaylist(ctx context.Context, newPls *model.Playlist)
owner, _ := request.UserFrom(ctx)
pls, err := s.ds.Playlist(ctx).FindByPath(newPls.Path)
if err != nil && err != model.ErrNotFound {
if err != nil && !errors.Is(err, model.ErrNotFound) {
return err
}
if err == nil && !pls.Sync {

View File

@ -2,6 +2,7 @@ package scrobbler
import (
"context"
"errors"
"time"
"github.com/navidrome/navidrome/log"
@ -92,16 +93,14 @@ func (b *bufferedScrobbler) processUserQueue(ctx context.Context, userId string)
MediaFile: entry.MediaFile,
TimeStamp: entry.PlayTime,
})
if errors.Is(err, ErrRetryLater) {
log.Warn(ctx, "Could not send scrobble. Will be retried", "userId", entry.UserID,
"track", entry.Title, "artist", entry.Artist, "scrobbler", b.service, err)
return false
}
if err != nil {
switch err {
case ErrRetryLater:
log.Warn(ctx, "Could not send scrobble. Will be retried", "userId", entry.UserID,
"track", entry.Title, "artist", entry.Artist, "scrobbler", b.service, err)
return false
default:
log.Error(ctx, "Error sending scrobble to service. Discarding", "scrobbler", b.service,
"userId", entry.UserID, "artist", entry.Artist, "track", entry.Title, err)
}
log.Error(ctx, "Error sending scrobble to service. Discarding", "scrobbler", b.service,
"userId", entry.UserID, "artist", entry.Artist, "track", entry.Title, err)
}
err = buffer.Dequeue(entry)
if err != nil {

View File

@ -2,6 +2,7 @@ package persistence
import (
"context"
"errors"
. "github.com/Masterminds/squirrel"
"github.com/beego/beego/v2/client/orm"
@ -102,7 +103,7 @@ func (r *playerRepository) Save(entity interface{}) (string, error) {
return "", rest.ErrPermissionDenied
}
id, err := r.put(t.ID, t)
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return "", rest.ErrNotFound
}
return id, err
@ -115,7 +116,7 @@ func (r *playerRepository) Update(id string, entity interface{}, cols ...string)
return rest.ErrPermissionDenied
}
_, err := r.put(id, t, cols...)
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return rest.ErrNotFound
}
return err
@ -124,7 +125,7 @@ func (r *playerRepository) Update(id string, entity interface{}, cols ...string)
func (r *playerRepository) Delete(id string) error {
filter := r.addRestriction(And{Eq{"id": id}})
err := r.delete(filter)
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return rest.ErrNotFound
}
return err

View File

@ -3,6 +3,7 @@ package persistence
import (
"context"
"encoding/json"
"errors"
"strings"
"time"
@ -395,7 +396,7 @@ func (r *playlistRepository) Update(id string, entity interface{}, cols ...strin
pls.ID = id
pls.UpdatedAt = time.Now()
_, err = r.put(id, pls, append(cols, "updatedAt")...)
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return rest.ErrNotFound
}
return err

View File

@ -2,6 +2,7 @@ package persistence
import (
"context"
"errors"
. "github.com/Masterminds/squirrel"
"github.com/beego/beego/v2/client/orm"
@ -48,7 +49,7 @@ func (r propertyRepository) Get(id string) (string, error) {
func (r propertyRepository) DefaultGet(id string, defaultValue string) (string, error) {
value, err := r.Get(id)
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return defaultValue, nil
}
if err != nil {

View File

@ -2,6 +2,7 @@ package persistence
import (
"context"
"errors"
"time"
. "github.com/Masterminds/squirrel"
@ -59,7 +60,7 @@ func (r *scrobbleBufferRepository) Next(service string, userId string) (*model.S
res := model.ScrobbleEntries{}
// TODO Rewrite queryOne to use QueryRows, to workaround the recursive embedded structs issue
err := r.queryAll(sql, &res)
if err == model.ErrNotFound || len(res) == 0 {
if errors.Is(err, model.ErrNotFound) || len(res) == 0 {
return nil, nil
}
if err != nil {

View File

@ -2,6 +2,7 @@ package persistence
import (
"context"
"errors"
. "github.com/Masterminds/squirrel"
"github.com/beego/beego/v2/client/orm"
@ -24,7 +25,7 @@ func NewShareRepository(ctx context.Context, o orm.QueryExecutor) model.ShareRep
func (r *shareRepository) Delete(id string) error {
err := r.delete(Eq{"id": id})
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return rest.ErrNotFound
}
return err
@ -50,7 +51,7 @@ func (r *shareRepository) Update(id string, entity interface{}, cols ...string)
s := entity.(*model.Share)
s.ID = id
_, err := r.put(id, s, cols...)
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return rest.ErrNotFound
}
return err
@ -59,7 +60,7 @@ func (r *shareRepository) Update(id string, entity interface{}, cols ...string)
func (r *shareRepository) Save(entity interface{}) (string, error) {
s := entity.(*model.Share)
id, err := r.put(s.ID, s)
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return "", rest.ErrNotFound
}
return id, err

View File

@ -1,6 +1,7 @@
package persistence
import (
"errors"
"time"
. "github.com/Masterminds/squirrel"
@ -35,7 +36,7 @@ func (r sqlRepository) annUpsert(values map[string]interface{}, itemIDs ...strin
upd = upd.Set(f, v)
}
c, err := r.executeSQL(upd)
if c == 0 || err == orm.ErrNoRows {
if c == 0 || errors.Is(err, orm.ErrNoRows) {
for _, itemID := range itemIDs {
values["ann_id"] = uuid.NewString()
values["user_id"] = userId(r.ctx)
@ -66,7 +67,7 @@ func (r sqlRepository) IncPlayCount(itemID string, ts time.Time) error {
Set("play_date", ts)
c, err := r.executeSQL(upd)
if c == 0 || err == orm.ErrNoRows {
if c == 0 || errors.Is(err, orm.ErrNoRows) {
values := map[string]interface{}{}
values["ann_id"] = uuid.NewString()
values["user_id"] = userId(r.ctx)

View File

@ -2,6 +2,7 @@ package persistence
import (
"context"
"errors"
"fmt"
"strings"
"time"
@ -146,7 +147,7 @@ func (r sqlRepository) queryOne(sq Sqlizer, response interface{}) error {
}
start := time.Now()
err = r.ormer.Raw(query, args...).QueryRow(response)
if err == orm.ErrNoRows {
if errors.Is(err, orm.ErrNoRows) {
r.logSQL(query, args, nil, 0, start)
return model.ErrNotFound
}
@ -161,7 +162,7 @@ func (r sqlRepository) queryAll(sq Sqlizer, response interface{}) error {
}
start := time.Now()
c, err := r.ormer.Raw(query, args...).QueryRows(response)
if err == orm.ErrNoRows {
if errors.Is(err, orm.ErrNoRows) {
r.logSQL(query, args, nil, c, start)
return model.ErrNotFound
}
@ -224,7 +225,7 @@ func (r sqlRepository) put(id string, m interface{}, colsToUpdate ...string) (ne
func (r sqlRepository) delete(cond Sqlizer) error {
del := Delete(r.tableName).Where(cond)
_, err := r.executeSQL(del)
if err == orm.ErrNoRows {
if errors.Is(err, orm.ErrNoRows) {
return model.ErrNotFound
}
return err

View File

@ -1,6 +1,7 @@
package persistence
import (
"errors"
"time"
. "github.com/Masterminds/squirrel"
@ -44,7 +45,7 @@ func (r sqlRepository) bmkUpsert(itemID, comment string, position int64) error {
if err == nil {
log.Debug(r.ctx, "Updated bookmark", "id", itemID, "user", user.UserName, "position", position, "comment", comment)
}
if c == 0 || err == orm.ErrNoRows {
if c == 0 || errors.Is(err, orm.ErrNoRows) {
values["user_id"] = user.ID
values["item_type"] = r.tableName
values["item_id"] = itemID

View File

@ -2,6 +2,7 @@ package persistence
import (
"context"
"errors"
. "github.com/Masterminds/squirrel"
"github.com/beego/beego/v2/client/orm"
@ -71,7 +72,7 @@ func (r *transcodingRepository) NewInstance() interface{} {
func (r *transcodingRepository) Save(entity interface{}) (string, error) {
t := entity.(*model.Transcoding)
id, err := r.put(t.ID, t)
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return "", rest.ErrNotFound
}
return id, err
@ -81,7 +82,7 @@ func (r *transcodingRepository) Update(id string, entity interface{}, cols ...st
t := entity.(*model.Transcoding)
t.ID = id
_, err := r.put(id, t)
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return rest.ErrNotFound
}
return err
@ -89,7 +90,7 @@ func (r *transcodingRepository) Update(id string, entity interface{}, cols ...st
func (r *transcodingRepository) Delete(id string) error {
err := r.delete(Eq{"id": id})
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return rest.ErrNotFound
}
return err

View File

@ -2,6 +2,7 @@ package persistence
import (
"context"
"errors"
. "github.com/Masterminds/squirrel"
"github.com/beego/beego/v2/client/orm"
@ -48,7 +49,7 @@ func (r userPropsRepository) Get(userId, key string) (string, error) {
func (r userPropsRepository) DefaultGet(userId, key string, defaultValue string) (string, error) {
value, err := r.Get(userId, key)
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return defaultValue, nil
}
if err != nil {

View File

@ -131,7 +131,7 @@ func (r *userRepository) Read(id string) (interface{}, error) {
return nil, rest.ErrPermissionDenied
}
usr, err := r.Get(id)
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return nil, rest.ErrNotFound
}
return usr, err
@ -195,7 +195,7 @@ func (r *userRepository) Update(id string, entity interface{}, cols ...string) e
return err
}
err := r.Put(u)
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return rest.ErrNotFound
}
return err
@ -225,7 +225,7 @@ func validatePasswordChange(newUser *model.User, logged *model.User) error {
func validateUsernameUnique(r model.UserRepository, u *model.User) error {
usr, err := r.FindByUsername(u.UserName)
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return nil
}
if err != nil {
@ -243,7 +243,7 @@ func (r *userRepository) Delete(id string) error {
return rest.ErrPermissionDenied
}
err := r.delete(Eq{"id": id})
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return rest.ErrNotFound
}
return err

View File

@ -156,7 +156,7 @@ func createAdminUser(ctx context.Context, ds model.DataStore, username, password
func validateLogin(userRepo model.UserRepository, userName, password string) (*model.User, error) {
u, err := userRepo.FindByUsernameWithPassword(userName)
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return nil, nil
}
if err != nil {

View File

@ -145,7 +145,7 @@ func (b *broker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
log.Trace(ctx, "Sending event to client", "event", *event, "client", c.String())
if err := writeEvent(w, *event, writeTimeOut); err == errWriteTimeOut {
if err := writeEvent(w, *event, writeTimeOut); errors.Is(err, errWriteTimeOut) {
log.Debug(ctx, "Timeout sending event to client", "event", *event, "client", c.String())
return
}

View File

@ -1,6 +1,7 @@
package server
import (
"errors"
"fmt"
"io/fs"
"net/http"
@ -118,7 +119,7 @@ func clientUniqueIdAdder(next http.Handler) http.Handler {
http.SetCookie(w, c)
} else {
c, err := r.Cookie(consts.UIClientUniqueIDHeader)
if err != http.ErrNoCookie {
if !errors.Is(err, http.ErrNoCookie) {
clientUniqueId = c.Value
}
}

View File

@ -3,6 +3,7 @@ package nativeapi
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
@ -47,7 +48,7 @@ func handleExportPlaylist(ds model.DataStore) http.HandlerFunc {
plsRepo := ds.Playlist(ctx)
plsId := chi.URLParam(r, "playlistId")
pls, err := plsRepo.GetWithTracks(plsId)
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
log.Warn("Playlist not found", "playlistId", plsId)
http.Error(w, "not found", http.StatusNotFound)
return
@ -89,7 +90,7 @@ func deleteFromPlaylist(ds model.DataStore) http.HandlerFunc {
tracksRepo := tx.Playlist(r.Context()).Tracks(playlistId)
return tracksRepo.Delete(ids...)
})
if len(ids) == 1 && err == model.ErrNotFound {
if len(ids) == 1 && errors.Is(err, model.ErrNotFound) {
log.Warn(r.Context(), "Track not found in playlist", "playlistId", playlistId, "id", ids[0])
http.Error(w, "not found", http.StatusNotFound)
return
@ -190,7 +191,7 @@ func reorderItem(ds model.DataStore) http.HandlerFunc {
}
tracksRepo := ds.Playlist(r.Context()).Tracks(playlistId)
err = tracksRepo.Reorder(id, newPos)
if err == rest.ErrPermissionDenied {
if errors.Is(err, rest.ErrPermissionDenied) {
http.Error(w, err.Error(), http.StatusForbidden)
return
}

View File

@ -3,6 +3,7 @@ package subsonic
import (
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"net/http"
"runtime"
@ -183,7 +184,7 @@ func h(r chi.Router, path string, f handler) {
if err != nil {
// If it is not a Subsonic error, convert it to an ErrorGeneric
if _, ok := err.(subError); !ok {
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
err = newError(responses.ErrorDataNotFound, "data not found")
} else {
err = newError(responses.ErrorGeneric, "Internal Error")

View File

@ -2,6 +2,7 @@ package subsonic
import (
"context"
"errors"
"net/http"
"strconv"
"time"
@ -104,11 +105,11 @@ func (c *BrowsingController) GetMusicDirectory(w http.ResponseWriter, r *http.Re
ctx := r.Context()
entity, err := core.GetEntityByID(ctx, c.ds, id)
switch {
case err == model.ErrNotFound:
if errors.Is(err, model.ErrNotFound) {
log.Error(r, "Requested ID not found ", "id", id)
return nil, newError(responses.ErrorDataNotFound, "Directory not found")
case err != nil:
}
if err != nil {
log.Error(err)
return nil, err
}
@ -140,11 +141,11 @@ func (c *BrowsingController) GetArtist(w http.ResponseWriter, r *http.Request) (
ctx := r.Context()
artist, err := c.ds.Artist(ctx).Get(id)
switch {
case err == model.ErrNotFound:
if errors.Is(err, model.ErrNotFound) {
log.Error(ctx, "Requested ArtistID not found ", "id", id)
return nil, newError(responses.ErrorDataNotFound, "Artist not found")
case err != nil:
}
if err != nil {
log.Error(ctx, "Error retrieving artist", "id", id, err)
return nil, err
}
@ -165,11 +166,11 @@ func (c *BrowsingController) GetAlbum(w http.ResponseWriter, r *http.Request) (*
ctx := r.Context()
album, err := c.ds.Album(ctx).Get(id)
switch {
case err == model.ErrNotFound:
if errors.Is(err, model.ErrNotFound) {
log.Error(ctx, "Requested AlbumID not found ", "id", id)
return nil, newError(responses.ErrorDataNotFound, "Album not found")
case err != nil:
}
if err != nil {
log.Error(ctx, "Error retrieving album", "id", id, err)
return nil, err
}
@ -190,11 +191,11 @@ func (c *BrowsingController) GetSong(w http.ResponseWriter, r *http.Request) (*r
ctx := r.Context()
mf, err := c.ds.MediaFile(ctx).Get(id)
switch {
case err == model.ErrNotFound:
if errors.Is(err, model.ErrNotFound) {
log.Error(r, "Requested MediaFileID not found ", "id", id)
return nil, newError(responses.ErrorDataNotFound, "Song not found")
case err != nil:
}
if err != nil {
log.Error(r, "Error retrieving MediaFile", "id", id, err)
return nil, err
}

View File

@ -2,6 +2,7 @@ package subsonic
import (
"context"
"errors"
"fmt"
"net/http"
"time"
@ -39,11 +40,11 @@ func (c *MediaAnnotationController) SetRating(w http.ResponseWriter, r *http.Req
log.Debug(r, "Setting rating", "rating", rating, "id", id)
err = c.setRating(r.Context(), id, rating)
switch {
case err == model.ErrNotFound:
if errors.Is(err, model.ErrNotFound) {
log.Error(r, err)
return nil, newError(responses.ErrorDataNotFound, "ID not found")
case err != nil:
}
if err != nil {
log.Error(r, err)
return nil, err
}
@ -161,11 +162,11 @@ func (c *MediaAnnotationController) setStar(ctx context.Context, star bool, ids
return nil
})
switch {
case err == model.ErrNotFound:
if errors.Is(err, model.ErrNotFound) {
log.Error(ctx, err)
return newError(responses.ErrorDataNotFound, "ID not found")
case err != nil:
}
if err != nil {
log.Error(ctx, err)
return err
}

View File

@ -1,6 +1,7 @@
package subsonic
import (
"errors"
"io"
"net/http"
"regexp"
@ -66,11 +67,11 @@ func (c *MediaRetrievalController) GetCoverArt(w http.ResponseWriter, r *http.Re
w.Header().Set("cache-control", "public, max-age=315360000")
imgReader, err := c.artwork.Get(r.Context(), id, size)
switch {
case err == model.ErrNotFound:
if errors.Is(err, model.ErrNotFound) {
log.Error(r, "Couldn't find coverArt", "id", id, err)
return nil, newError(responses.ErrorDataNotFound, "Artwork not found")
case err != nil:
}
if err != nil {
log.Error(r, "Error retrieving coverArt", "id", id, err)
return nil, err
}

View File

@ -4,6 +4,7 @@ import (
"context"
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"net"
"net/http"
@ -78,7 +79,7 @@ func authenticate(ds model.DataStore) func(next http.Handler) http.Handler {
jwt := utils.ParamString(r, "jwt")
usr, err := validateUser(ctx, ds, username, pass, token, salt, jwt)
if err == model.ErrInvalidAuth {
if errors.Is(err, model.ErrInvalidAuth) {
log.Warn(ctx, "API: Invalid login", "username", username, "remoteAddr", r.RemoteAddr, err)
} else if err != nil {
log.Error(ctx, "API: Error authenticating username", "username", username, "remoteAddr", r.RemoteAddr, err)
@ -107,7 +108,7 @@ func authenticate(ds model.DataStore) func(next http.Handler) http.Handler {
func validateUser(ctx context.Context, ds model.DataStore, username, pass, token, salt, jwt string) (*model.User, error) {
user, err := ds.User(ctx).FindByUsernameWithPassword(username)
if err == model.ErrNotFound {
if errors.Is(err, model.ErrNotFound) {
return nil, model.ErrInvalidAuth
}
if err != nil {

View File

@ -49,11 +49,11 @@ func (c *PlaylistsController) GetPlaylist(w http.ResponseWriter, r *http.Request
func (c *PlaylistsController) getPlaylist(ctx context.Context, id string) (*responses.Subsonic, error) {
pls, err := c.ds.Playlist(ctx).GetWithTracks(id)
switch {
case err == model.ErrNotFound:
if errors.Is(err, model.ErrNotFound) {
log.Error(ctx, err.Error(), "id", id)
return nil, newError(responses.ErrorDataNotFound, "Directory not found")
case err != nil:
}
if err != nil {
log.Error(ctx, err)
return nil, err
}
@ -113,7 +113,7 @@ func (c *PlaylistsController) DeletePlaylist(w http.ResponseWriter, r *http.Requ
return nil, err
}
err = c.ds.Playlist(r.Context()).Delete(id)
if err == model.ErrNotAuthorized {
if errors.Is(err, model.ErrNotAuthorized) {
return nil, newError(responses.ErrorAuthorizationFail)
}
if err != nil {
@ -152,7 +152,7 @@ func (c *PlaylistsController) UpdatePlaylist(w http.ResponseWriter, r *http.Requ
log.Trace(r, fmt.Sprintf("-- Removing: '%v'", songIndexesToRemove))
err = c.pls.Update(r.Context(), playlistId, plsName, comment, public, songsToAdd, songIndexesToRemove)
if err == model.ErrNotAuthorized {
if errors.Is(err, model.ErrNotAuthorized) {
return nil, newError(responses.ErrorAuthorizationFail)
}
if err != nil {