Chore: Enable errorlint linter (#29227)

* Enable errorlint linter
* Handle wrapped errors

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>
Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com>
This commit is contained in:
Arve Knudsen
2020-11-19 14:47:17 +01:00
committed by GitHub
parent 993adb72e0
commit 9593d57914
34 changed files with 142 additions and 101 deletions

View File

@@ -1,6 +1,7 @@
package conditions
import (
"errors"
"fmt"
"strings"
"time"
@@ -158,7 +159,7 @@ func (c *QueryCondition) executeQuery(context *alerting.EvalContext, timeRange *
resp, err := c.HandleRequest(context.Ctx, getDsInfo.Result, req)
if err != nil {
if err == gocontext.DeadlineExceeded {
if errors.Is(err, gocontext.DeadlineExceeded) {
return nil, fmt.Errorf("alert execution exceeded the timeout")
}

View File

@@ -167,7 +167,7 @@ func (e *DashAlertExtractor) getAlertFromPanels(jsonWithPanels *simplejson.Json,
}
if err := bus.Dispatch(&dsFilterQuery); err != nil {
if err != bus.ErrHandlerNotFound {
if !errors.Is(err, bus.ErrHandlerNotFound) {
return nil, err
}
} else {

View File

@@ -2,6 +2,7 @@ package alerting
import (
"context"
"errors"
"fmt"
"time"
@@ -159,11 +160,11 @@ func (n *notificationService) sendNotification(evalContext *EvalContext, notifie
}
err := bus.DispatchCtx(evalContext.Ctx, setPendingCmd)
if err == models.ErrAlertNotificationStateVersionConflict {
return nil
}
if err != nil {
if errors.Is(err, models.ErrAlertNotificationStateVersionConflict) {
return nil
}
return err
}

View File

@@ -1,6 +1,7 @@
package notifiers
import (
"errors"
"testing"
"github.com/grafana/grafana/pkg/components/simplejson"
@@ -70,7 +71,9 @@ func TestThreemaNotifier(t *testing.T) {
not, err := NewThreemaNotifier(model)
So(not, ShouldBeNil)
So(err.(alerting.ValidationError).Reason, ShouldEqual, "Invalid Threema Gateway ID: Must start with a *")
var valErr alerting.ValidationError
So(errors.As(err, &valErr), ShouldBeTrue)
So(valErr.Reason, ShouldEqual, "Invalid Threema Gateway ID: Must start with a *")
})
Convey("invalid Threema Gateway IDs should be rejected (length)", func() {
@@ -90,7 +93,9 @@ func TestThreemaNotifier(t *testing.T) {
not, err := NewThreemaNotifier(model)
So(not, ShouldBeNil)
So(err.(alerting.ValidationError).Reason, ShouldEqual, "Invalid Threema Gateway ID: Must be 8 characters long")
var valErr alerting.ValidationError
So(errors.As(err, &valErr), ShouldBeTrue)
So(valErr.Reason, ShouldEqual, "Invalid Threema Gateway ID: Must be 8 characters long")
})
Convey("invalid Threema Recipient IDs should be rejected (length)", func() {
@@ -110,7 +115,9 @@ func TestThreemaNotifier(t *testing.T) {
not, err := NewThreemaNotifier(model)
So(not, ShouldBeNil)
So(err.(alerting.ValidationError).Reason, ShouldEqual, "Invalid Threema Recipient ID: Must be 8 characters long")
var valErr alerting.ValidationError
So(errors.As(err, &valErr), ShouldBeTrue)
So(valErr.Reason, ShouldEqual, "Invalid Threema Recipient ID: Must be 8 characters long")
})
})
})

View File

@@ -59,12 +59,12 @@ func (handler *defaultResultHandler) handle(evalContext *EvalContext) error {
}
if err := bus.Dispatch(cmd); err != nil {
if err == models.ErrCannotChangeStateOnPausedAlert {
if errors.Is(err, models.ErrCannotChangeStateOnPausedAlert) {
handler.log.Error("Cannot change state on alert that's paused", "error", err)
return err
}
if err == models.ErrRequiresNewState {
if errors.Is(err, models.ErrRequiresNewState) {
handler.log.Info("Alert already updated")
return nil
}

View File

@@ -7,6 +7,8 @@ import (
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/sqlstore"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type FakeCondition struct{}
@@ -34,15 +36,15 @@ func TestAlertRuleFrequencyParsing(t *testing.T) {
}
for _, tc := range tcs {
r, err := getTimeDurationStringToSeconds(tc.input)
if err != tc.err {
t.Errorf("expected error: '%v' got: '%v'", tc.err, err)
return
}
if r != tc.result {
t.Errorf("expected result: %d got %d", tc.result, r)
}
t.Run(tc.input, func(t *testing.T) {
r, err := getTimeDurationStringToSeconds(tc.input)
if tc.err == nil {
require.NoError(t, err)
} else {
require.EqualError(t, err, tc.err.Error())
}
assert.Equal(t, tc.result, r)
})
}
}

View File

@@ -1,6 +1,8 @@
package dashboards
import (
"errors"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/guardian"
@@ -209,31 +211,31 @@ func dashToFolder(dash *models.Dashboard) *models.Folder {
}
func toFolderError(err error) error {
if err == models.ErrDashboardTitleEmpty {
if errors.Is(err, models.ErrDashboardTitleEmpty) {
return models.ErrFolderTitleEmpty
}
if err == models.ErrDashboardUpdateAccessDenied {
if errors.Is(err, models.ErrDashboardUpdateAccessDenied) {
return models.ErrFolderAccessDenied
}
if err == models.ErrDashboardWithSameNameInFolderExists {
if errors.Is(err, models.ErrDashboardWithSameNameInFolderExists) {
return models.ErrFolderSameNameExists
}
if err == models.ErrDashboardWithSameUIDExists {
if errors.Is(err, models.ErrDashboardWithSameUIDExists) {
return models.ErrFolderWithSameUIDExists
}
if err == models.ErrDashboardVersionMismatch {
if errors.Is(err, models.ErrDashboardVersionMismatch) {
return models.ErrFolderVersionMismatch
}
if err == models.ErrDashboardNotFound {
if errors.Is(err, models.ErrDashboardNotFound) {
return models.ErrFolderNotFound
}
if err == models.ErrDashboardFailedGenerateUniqueUid {
if errors.Is(err, models.ErrDashboardFailedGenerateUniqueUid) {
err = models.ErrFolderFailedGenerateUniqueUid
}

View File

@@ -5,6 +5,7 @@ import (
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/models"
"github.com/stretchr/testify/assert"
"github.com/grafana/grafana/pkg/services/guardian"
@@ -194,9 +195,8 @@ func TestFolderService(t *testing.T) {
for _, tc := range testCases {
actualError := toFolderError(tc.ActualError)
if actualError != tc.ExpectedError {
t.Errorf("For error '%s' expected error '%s', actual '%s'", tc.ActualError, tc.ExpectedError, actualError)
}
assert.EqualErrorf(t, actualError, tc.ExpectedError.Error(),
"For error '%s' expected error '%s', actual '%s'", tc.ActualError, tc.ExpectedError, actualError)
}
})
})

View File

@@ -1,6 +1,7 @@
package guardian
import (
"errors"
"fmt"
"runtime"
"testing"
@@ -300,7 +301,7 @@ func (sc *scenarioContext) verifyDuplicatePermissionsShouldNotBeAllowed() {
sc.updatePermissions = p
_, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, p)
if err != ErrGuardianPermissionExists {
if !errors.Is(err, ErrGuardianPermissionExists) {
sc.reportFailure(tc, ErrGuardianPermissionExists, err)
}
sc.reportSuccess()
@@ -314,8 +315,7 @@ func (sc *scenarioContext) verifyDuplicatePermissionsShouldNotBeAllowed() {
}
sc.updatePermissions = p
_, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, p)
if err != ErrGuardianPermissionExists {
if !errors.Is(err, ErrGuardianPermissionExists) {
sc.reportFailure(tc, ErrGuardianPermissionExists, err)
}
sc.reportSuccess()
@@ -330,7 +330,7 @@ func (sc *scenarioContext) verifyDuplicatePermissionsShouldNotBeAllowed() {
sc.updatePermissions = p
_, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, p)
if err != ErrGuardianPermissionExists {
if !errors.Is(err, ErrGuardianPermissionExists) {
sc.reportFailure(tc, ErrGuardianPermissionExists, err)
}
sc.reportSuccess()
@@ -344,8 +344,7 @@ func (sc *scenarioContext) verifyDuplicatePermissionsShouldNotBeAllowed() {
}
sc.updatePermissions = p
_, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, p)
if err != ErrGuardianPermissionExists {
if !errors.Is(err, ErrGuardianPermissionExists) {
sc.reportFailure(tc, ErrGuardianPermissionExists, err)
}
sc.reportSuccess()
@@ -358,8 +357,7 @@ func (sc *scenarioContext) verifyDuplicatePermissionsShouldNotBeAllowed() {
}
sc.updatePermissions = p
_, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, p)
if err != ErrGuardianPermissionExists {
if !errors.Is(err, ErrGuardianPermissionExists) {
sc.reportFailure(tc, ErrGuardianPermissionExists, err)
}
sc.reportSuccess()
@@ -402,7 +400,6 @@ func (sc *scenarioContext) verifyUpdateDashboardPermissionsShouldBeAllowed(pt pe
sc.updatePermissions = permissionList
ok, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList)
if err != nil {
sc.reportFailure(tc, nil, err)
}
@@ -442,7 +439,6 @@ func (sc *scenarioContext) verifyUpdateDashboardPermissionsShouldNotBeAllowed(pt
sc.updatePermissions = permissionList
ok, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList)
if err != nil {
sc.reportFailure(tc, nil, err)
}
@@ -505,7 +501,6 @@ func (sc *scenarioContext) verifyUpdateChildDashboardPermissionsShouldBeAllowed(
sc.updatePermissions = permissionList
ok, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList)
if err != nil {
sc.reportFailure(tc, nil, err)
}
@@ -568,7 +563,6 @@ func (sc *scenarioContext) verifyUpdateChildDashboardPermissionsShouldNotBeAllow
sc.updatePermissions = permissionList
ok, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList)
if err != nil {
sc.reportFailure(tc, nil, err)
}
@@ -616,8 +610,7 @@ func (sc *scenarioContext) verifyUpdateChildDashboardPermissionsWithOverrideShou
sc.updatePermissions = permissionList
_, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList)
if err != ErrGuardianOverride {
if !errors.Is(err, ErrGuardianOverride) {
sc.reportFailure(tc, ErrGuardianOverride, err)
}
sc.reportSuccess()
@@ -665,7 +658,6 @@ func (sc *scenarioContext) verifyUpdateChildDashboardPermissionsWithOverrideShou
}
sc.updatePermissions = permissionList
ok, err := sc.g.CheckPermissionBeforeUpdate(models.PERMISSION_ADMIN, permissionList)
if err != nil {
sc.reportFailure(tc, nil, err)
}

View File

@@ -475,11 +475,11 @@ func (server *Server) AdminBind() error {
func (server *Server) userBind(path, password string) error {
err := server.Connection.Bind(path, password)
if err != nil {
if ldapErr, ok := err.(*ldap.Error); ok {
if ldapErr.ResultCode == 49 {
return ErrInvalidCredentials
}
var ldapErr *ldap.Error
if errors.As(err, &ldapErr) && ldapErr.ResultCode == 49 {
return ErrInvalidCredentials
}
return err
}

View File

@@ -234,7 +234,7 @@ func isSilentError(err error) bool {
continueErrs := []error{ErrInvalidCredentials, ErrCouldNotFindUser}
for _, cerr := range continueErrs {
if err == cerr {
if errors.Is(err, cerr) {
return true
}
}

View File

@@ -2,6 +2,7 @@ package oauthtoken
import (
"context"
"errors"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/log"
@@ -23,7 +24,7 @@ func GetCurrentOAuthToken(ctx context.Context, user *models.SignedInUser) *oauth
authInfoQuery := &models.GetAuthInfoQuery{UserId: user.UserId}
if err := bus.Dispatch(authInfoQuery); err != nil {
if err == models.ErrUserNotFound {
if errors.Is(err, models.ErrUserNotFound) {
// Not necessarily an error. User may be logged in another way.
logger.Debug("no OAuth token for user found", "userId", user.UserId, "username", user.Login)
} else {

View File

@@ -117,8 +117,7 @@ func (fr *FileReader) startWalkingDisk() error {
// storeDashboardsInFolder saves dashboards from the filesystem on disk to the folder from config
func (fr *FileReader) storeDashboardsInFolder(filesFoundOnDisk map[string]os.FileInfo, dashboardRefs map[string]*models.DashboardProvisioning, sanityChecker *provisioningSanityChecker) error {
folderID, err := getOrCreateFolderID(fr.Cfg, fr.dashboardProvisioningService, fr.Cfg.Folder)
if err != nil && err != ErrFolderNameMissing {
if err != nil && !errors.Is(err, ErrFolderNameMissing) {
return err
}
@@ -145,7 +144,7 @@ func (fr *FileReader) storeDashboardsInFoldersFromFileStructure(filesFoundOnDisk
}
folderID, err := getOrCreateFolderID(fr.Cfg, fr.dashboardProvisioningService, folderName)
if err != nil && err != ErrFolderNameMissing {
if err != nil && !errors.Is(err, ErrFolderNameMissing) {
return fmt.Errorf("can't provision folder %q from file system structure: %w", folderName, err)
}
@@ -264,12 +263,12 @@ func getOrCreateFolderID(cfg *config, service dashboards.DashboardProvisioningSe
cmd := &models.GetDashboardQuery{Slug: models.SlugifyTitle(folderName), OrgId: cfg.OrgID}
err := bus.Dispatch(cmd)
if err != nil && err != models.ErrDashboardNotFound {
if err != nil && !errors.Is(err, models.ErrDashboardNotFound) {
return 0, err
}
// dashboard folder not found. create one.
if err == models.ErrDashboardNotFound {
if errors.Is(err, models.ErrDashboardNotFound) {
dash := &dashboards.SaveDashboardDTO{}
dash.Dashboard = models.NewDashboardFolder(folderName)
dash.Dashboard.IsFolder = true

View File

@@ -45,11 +45,11 @@ func (dc *DatasourceProvisioner) apply(cfg *configs) error {
for _, ds := range cfg.Datasources {
cmd := &models.GetDataSourceByNameQuery{OrgId: ds.OrgID, Name: ds.Name}
err := bus.Dispatch(cmd)
if err != nil && err != models.ErrDataSourceNotFound {
if err != nil && !errors.Is(err, models.ErrDataSourceNotFound) {
return err
}
if err == models.ErrDataSourceNotFound {
if errors.Is(err, models.ErrDataSourceNotFound) {
dc.log.Info("inserting datasource from configuration ", "name", ds.Name, "uid", ds.UID)
insertCmd := createInsertCommand(ds)
if err := bus.Dispatch(insertCmd); err != nil {

View File

@@ -1,6 +1,8 @@
package plugins
import (
"errors"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
@@ -42,7 +44,7 @@ func (ap *PluginProvisioner) apply(cfg *pluginsAsConfig) error {
query := &models.GetPluginSettingByIdQuery{OrgId: app.OrgID, PluginId: app.PluginID}
err := bus.Dispatch(query)
if err != nil {
if err != models.ErrPluginSettingNotFound {
if !errors.Is(err, models.ErrPluginSettingNotFound) {
return err
}
} else {

View File

@@ -2,6 +2,7 @@ package rendering
import (
"context"
"errors"
"fmt"
"io"
"net"
@@ -79,7 +80,7 @@ func (rs *RenderingService) renderViaHttp(ctx context.Context, renderKey string,
defer resp.Body.Close()
// check for timeout first
if reqContext.Err() == context.DeadlineExceeded {
if errors.Is(reqContext.Err(), context.DeadlineExceeded) {
rs.log.Info("Rendering timed out")
return nil, ErrTimeout
}
@@ -99,7 +100,7 @@ func (rs *RenderingService) renderViaHttp(ctx context.Context, renderKey string,
_, err = io.Copy(out, resp.Body)
if err != nil {
// check that we didn't timeout while receiving the response.
if reqContext.Err() == context.DeadlineExceeded {
if errors.Is(reqContext.Err(), context.DeadlineExceeded) {
rs.log.Info("Rendering timed out")
return nil, ErrTimeout
}

View File

@@ -2,6 +2,7 @@ package rendering
import (
"context"
"errors"
"fmt"
"time"
@@ -45,7 +46,7 @@ func (rs *RenderingService) renderViaPluginV1(ctx context.Context, renderKey str
rs.log.Debug("calling renderer plugin", "req", req)
rsp, err := rs.pluginInfo.GrpcPluginV1.Render(ctx, req)
if ctx.Err() == context.DeadlineExceeded {
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
rs.log.Info("Rendering timed out")
return nil, ErrTimeout
}
@@ -88,7 +89,7 @@ func (rs *RenderingService) renderViaPluginV2(ctx context.Context, renderKey str
rs.log.Debug("Calling renderer plugin", "req", req)
rsp, err := rs.pluginInfo.GrpcPluginV2.Render(ctx, req)
if ctx.Err() == context.DeadlineExceeded {
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
rs.log.Info("Rendering timed out")
return nil, ErrTimeout
}

View File

@@ -2,6 +2,7 @@ package rendering
import (
"context"
"errors"
"fmt"
"math"
"net/url"
@@ -136,7 +137,7 @@ func (rs *RenderingService) Render(ctx context.Context, opts Opts) (*RenderResul
elapsedTime := time.Since(startTime).Milliseconds()
result, err := rs.render(ctx, opts)
if err != nil {
if err == ErrTimeout {
if errors.Is(err, ErrTimeout) {
metrics.MRenderingRequestTotal.WithLabelValues("timeout").Inc()
metrics.MRenderingSummary.WithLabelValues("timeout").Observe(float64(elapsedTime))
} else {

View File

@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"time"
"github.com/gchaincl/sqlhooks"
@@ -87,7 +88,7 @@ func (h *databaseQueryWrapper) After(ctx context.Context, query string, args ...
func (h *databaseQueryWrapper) OnError(ctx context.Context, err error, query string, args ...interface{}) error {
status := "error"
// https://golang.org/pkg/database/sql/driver/#ErrSkip
if err == nil || err == driver.ErrSkip {
if err == nil || errors.Is(err, driver.ErrSkip) {
status = "success"
}

View File

@@ -1,6 +1,7 @@
package migrator
import (
"errors"
"time"
_ "github.com/go-sql-driver/mysql"
@@ -168,8 +169,8 @@ func (mg *Migrator) inTransaction(callback dbTransactionFunc) error {
}
if err := callback(sess); err != nil {
if rollErr := sess.Rollback(); err != rollErr {
return errutil.Wrapf(err, "Failed to roll back transaction due to error: %s", rollErr)
if rollErr := sess.Rollback(); !errors.Is(err, rollErr) {
return errutil.Wrapf(err, "failed to roll back transaction due to error: %s", rollErr)
}
return err

View File

@@ -1,6 +1,7 @@
package migrator
import (
"errors"
"fmt"
"strconv"
"strings"
@@ -169,7 +170,8 @@ func (db *MySQLDialect) TruncateDBTables() error {
}
func (db *MySQLDialect) isThisError(err error, errcode uint16) bool {
if driverErr, ok := err.(*mysql.MySQLError); ok {
var driverErr *mysql.MySQLError
if errors.As(err, &driverErr) {
if driverErr.Number == errcode {
return true
}
@@ -183,7 +185,8 @@ func (db *MySQLDialect) IsUniqueConstraintViolation(err error) bool {
}
func (db *MySQLDialect) ErrorMessage(err error) string {
if driverErr, ok := err.(*mysql.MySQLError); ok {
var driverErr *mysql.MySQLError
if errors.As(err, &driverErr) {
return driverErr.Message
}
return ""

View File

@@ -1,6 +1,7 @@
package migrator
import (
"errors"
"fmt"
"strconv"
"strings"
@@ -172,7 +173,8 @@ func (db *PostgresDialect) TruncateDBTables() error {
}
func (db *PostgresDialect) isThisError(err error, errcode string) bool {
if driverErr, ok := err.(*pq.Error); ok {
var driverErr *pq.Error
if errors.As(err, &driverErr) {
if string(driverErr.Code) == errcode {
return true
}
@@ -182,7 +184,8 @@ func (db *PostgresDialect) isThisError(err error, errcode string) bool {
}
func (db *PostgresDialect) ErrorMessage(err error) string {
if driverErr, ok := err.(*pq.Error); ok {
var driverErr *pq.Error
if errors.As(err, &driverErr) {
return driverErr.Message
}
return ""

View File

@@ -1,6 +1,7 @@
package migrator
import (
"errors"
"fmt"
"github.com/grafana/grafana/pkg/util/errutil"
@@ -120,7 +121,8 @@ func (db *SQLite3) TruncateDBTables() error {
}
func (db *SQLite3) isThisError(err error, errcode int) bool {
if driverErr, ok := err.(sqlite3.Error); ok {
var driverErr sqlite3.Error
if errors.As(err, &driverErr) {
if int(driverErr.ExtendedCode) == errcode {
return true
}
@@ -130,7 +132,8 @@ func (db *SQLite3) isThisError(err error, errcode int) bool {
}
func (db *SQLite3) ErrorMessage(err error) string {
if driverErr, ok := err.(sqlite3.Error); ok {
var driverErr sqlite3.Error
if errors.As(err, &driverErr) {
return driverErr.Error()
}
return ""

View File

@@ -2,6 +2,7 @@ package sqlstore
import (
"context"
"errors"
"time"
"github.com/grafana/grafana/pkg/bus"
@@ -42,8 +43,8 @@ func inTransactionWithRetryCtx(ctx context.Context, engine *xorm.Engine, callbac
err = callback(sess)
// special handling of database locked errors for sqlite, then we can retry 5 times
if sqlError, ok := err.(sqlite3.Error); ok && retry < 5 && sqlError.Code ==
sqlite3.ErrLocked || sqlError.Code == sqlite3.ErrBusy {
var sqlError sqlite3.Error
if errors.As(err, &sqlError) && retry < 5 && sqlError.Code == sqlite3.ErrLocked || sqlError.Code == sqlite3.ErrBusy {
if rollErr := sess.Rollback(); rollErr != nil {
return errutil.Wrapf(err, "Rolling back transaction due to error failed: %s", rollErr)
}

View File

@@ -2,6 +2,7 @@ package sqlstore
import (
"encoding/base64"
"errors"
"time"
"github.com/grafana/grafana/pkg/bus"
@@ -33,7 +34,7 @@ func GetUserByAuthInfo(query *models.GetUserByAuthInfoQuery) error {
authQuery.AuthId = query.AuthId
err = GetAuthInfo(authQuery)
if err != models.ErrUserNotFound {
if !errors.Is(err, models.ErrUserNotFound) {
if err != nil {
return err
}