Commit 16c185c3 by Arve Knudsen Committed by GitHub

Chore: Drop xerrors dependency (#26718)

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>
parent 5a6afd90
...@@ -81,7 +81,6 @@ require ( ...@@ -81,7 +81,6 @@ require (
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208 golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208
golang.org/x/tools v0.0.0-20200708183856-df98bc6d456c // indirect golang.org/x/tools v0.0.0-20200708183856-df98bc6d456c // indirect
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543
google.golang.org/grpc v1.29.1 google.golang.org/grpc v1.29.1
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d // indirect gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d // indirect
......
...@@ -17,7 +17,6 @@ import ( ...@@ -17,7 +17,6 @@ import (
"github.com/fatih/color" "github.com/fatih/color"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/utils" "github.com/grafana/grafana/pkg/cmd/grafana-cli/utils"
"github.com/grafana/grafana/pkg/util/errutil" "github.com/grafana/grafana/pkg/util/errutil"
"golang.org/x/xerrors"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/logger" "github.com/grafana/grafana/pkg/cmd/grafana-cli/logger"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/models" "github.com/grafana/grafana/pkg/cmd/grafana-cli/models"
...@@ -180,7 +179,7 @@ func SelectVersion(plugin *models.Plugin, version string) (*models.Version, erro ...@@ -180,7 +179,7 @@ func SelectVersion(plugin *models.Plugin, version string) (*models.Version, erro
latestForArch := latestSupportedVersion(plugin) latestForArch := latestSupportedVersion(plugin)
if latestForArch == nil { if latestForArch == nil {
return nil, xerrors.New("plugin is not supported on your architecture and OS.") return nil, fmt.Errorf("plugin is not supported on your architecture and OS")
} }
if version == "" { if version == "" {
...@@ -194,11 +193,13 @@ func SelectVersion(plugin *models.Plugin, version string) (*models.Version, erro ...@@ -194,11 +193,13 @@ func SelectVersion(plugin *models.Plugin, version string) (*models.Version, erro
} }
if len(ver.Version) == 0 { if len(ver.Version) == 0 {
return nil, xerrors.New("could not find the version you're looking for") return nil, fmt.Errorf("could not find the version you're looking for")
} }
if !supportsCurrentArch(&ver) { if !supportsCurrentArch(&ver) {
return nil, xerrors.Errorf("the version you want is not supported on your architecture and OS. Latest suitable version is %s", latestForArch.Version) return nil, fmt.Errorf(
"the version you want is not supported on your architecture and OS, latest suitable version is %s",
latestForArch.Version)
} }
return &ver, nil return &ver, nil
...@@ -209,7 +210,7 @@ func RemoveGitBuildFromName(pluginName, filename string) string { ...@@ -209,7 +210,7 @@ func RemoveGitBuildFromName(pluginName, filename string) string {
return r.ReplaceAllString(filename, pluginName+"/") return r.ReplaceAllString(filename, pluginName+"/")
} }
var permissionsDeniedMessage = "Could not create %s. Permission denied. Make sure you have write access to plugindir" const permissionsDeniedMessage = "could not create %q, permission denied, make sure you have write access to plugin dir"
func extractFiles(archiveFile string, pluginName string, filePath string, allowSymlinks bool) error { func extractFiles(archiveFile string, pluginName string, filePath string, allowSymlinks bool) error {
logger.Debugf("Extracting archive %v to %v...\n", archiveFile, filePath) logger.Debugf("Extracting archive %v to %v...\n", archiveFile, filePath)
...@@ -221,7 +222,8 @@ func extractFiles(archiveFile string, pluginName string, filePath string, allowS ...@@ -221,7 +222,8 @@ func extractFiles(archiveFile string, pluginName string, filePath string, allowS
for _, zf := range r.File { for _, zf := range r.File {
newFileName := RemoveGitBuildFromName(pluginName, zf.Name) newFileName := RemoveGitBuildFromName(pluginName, zf.Name)
if !isPathSafe(newFileName, filepath.Join(filePath, pluginName)) { if !isPathSafe(newFileName, filepath.Join(filePath, pluginName)) {
return xerrors.Errorf("filepath: %q tries to write outside of plugin directory: %q. This can be a security risk.", zf.Name, path.Join(filePath, pluginName)) return fmt.Errorf("filepath: %q tries to write outside of plugin directory: %q, this can be a security risk",
zf.Name, filepath.Join(filePath, pluginName))
} }
newFile := path.Join(filePath, newFileName) newFile := path.Join(filePath, newFileName)
...@@ -285,12 +287,12 @@ func extractFile(file *zip.File, filePath string) (err error) { ...@@ -285,12 +287,12 @@ func extractFile(file *zip.File, filePath string) (err error) {
dst, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, fileMode) dst, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, fileMode)
if err != nil { if err != nil {
if os.IsPermission(err) { if os.IsPermission(err) {
return xerrors.Errorf(permissionsDeniedMessage, filePath) return fmt.Errorf(permissionsDeniedMessage, filePath)
} }
unwrappedError := xerrors.Unwrap(err) unwrappedError := errors.Unwrap(err)
if unwrappedError != nil && strings.EqualFold(unwrappedError.Error(), "text file busy") { if unwrappedError != nil && strings.EqualFold(unwrappedError.Error(), "text file busy") {
return fmt.Errorf("file %s is in use. Please stop Grafana, install the plugin and restart Grafana", filePath) return fmt.Errorf("file %q is in use - please stop Grafana, install the plugin and restart Grafana", filePath)
} }
return errutil.Wrap("failed to open file", err) return errutil.Wrap("failed to open file", err)
......
...@@ -16,7 +16,6 @@ import ( ...@@ -16,7 +16,6 @@ import (
"github.com/grafana/grafana/pkg/cmd/grafana-cli/logger" "github.com/grafana/grafana/pkg/cmd/grafana-cli/logger"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/models" "github.com/grafana/grafana/pkg/cmd/grafana-cli/models"
"github.com/grafana/grafana/pkg/util/errutil" "github.com/grafana/grafana/pkg/util/errutil"
"golang.org/x/xerrors"
) )
type GrafanaComClient struct { type GrafanaComClient struct {
...@@ -78,7 +77,7 @@ func (client *GrafanaComClient) DownloadFile(pluginName string, tmpFile *os.File ...@@ -78,7 +77,7 @@ func (client *GrafanaComClient) DownloadFile(pluginName string, tmpFile *os.File
client.retryCount = 0 client.retryCount = 0
failure := fmt.Sprintf("%v", r) failure := fmt.Sprintf("%v", r)
if failure == "runtime error: makeslice: len out of range" { if failure == "runtime error: makeslice: len out of range" {
err = xerrors.New("Corrupt http response from source. Please try again") err = fmt.Errorf("corrupt HTTP response from source, please try again")
} else { } else {
panic(r) panic(r)
} }
...@@ -101,7 +100,7 @@ func (client *GrafanaComClient) DownloadFile(pluginName string, tmpFile *os.File ...@@ -101,7 +100,7 @@ func (client *GrafanaComClient) DownloadFile(pluginName string, tmpFile *os.File
} }
w.Flush() w.Flush()
if len(checksum) > 0 && checksum != fmt.Sprintf("%x", h.Sum(nil)) { if len(checksum) > 0 && checksum != fmt.Sprintf("%x", h.Sum(nil)) {
return xerrors.New("Expected MD5 checksum does not match the downloaded archive. Please contact security@grafana.com.") return fmt.Errorf("expected MD5 checksum does not match the downloaded archive - please contact security@grafana.com")
} }
return nil return nil
} }
......
...@@ -6,7 +6,7 @@ import ( ...@@ -6,7 +6,7 @@ import (
"path/filepath" "path/filepath"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/logger" "github.com/grafana/grafana/pkg/cmd/grafana-cli/logger"
"golang.org/x/xerrors" "github.com/grafana/grafana/pkg/util/errutil"
) )
func GetGrafanaPluginDir(currentOS string) string { func GetGrafanaPluginDir(currentOS string) string {
...@@ -23,7 +23,7 @@ func GetGrafanaPluginDir(currentOS string) string { ...@@ -23,7 +23,7 @@ func GetGrafanaPluginDir(currentOS string) string {
func getGrafanaRoot() (string, error) { func getGrafanaRoot() (string, error) {
ex, err := os.Executable() ex, err := os.Executable()
if err != nil { if err != nil {
return "", xerrors.New("Failed to get executable path") return "", errutil.Wrap("failed to get executable path", err)
} }
exPath := filepath.Dir(ex) exPath := filepath.Dir(ex)
_, last := path.Split(exPath) _, last := path.Split(exPath)
......
...@@ -2,6 +2,7 @@ package main ...@@ -2,6 +2,7 @@ package main
import ( import (
"context" "context"
"errors"
"flag" "flag"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
...@@ -40,7 +41,6 @@ import ( ...@@ -40,7 +41,6 @@ import (
_ "github.com/grafana/grafana/pkg/services/sqlstore" _ "github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util/errutil" "github.com/grafana/grafana/pkg/util/errutil"
"golang.org/x/xerrors"
) )
// NewServer returns a new instance of Server. // NewServer returns a new instance of Server.
...@@ -147,7 +147,7 @@ func (s *Server) Run() (err error) { ...@@ -147,7 +147,7 @@ func (s *Server) Run() (err error) {
defer func() { defer func() {
s.log.Debug("Waiting on services...") s.log.Debug("Waiting on services...")
if waitErr := s.childRoutines.Wait(); waitErr != nil && !xerrors.Is(waitErr, context.Canceled) { if waitErr := s.childRoutines.Wait(); waitErr != nil && !errors.Is(waitErr, context.Canceled) {
s.log.Error("A service failed", "err", waitErr) s.log.Error("A service failed", "err", waitErr)
if err == nil { if err == nil {
err = waitErr err = waitErr
...@@ -169,7 +169,7 @@ func (s *Server) Shutdown(reason string) { ...@@ -169,7 +169,7 @@ func (s *Server) Shutdown(reason string) {
s.shutdownFn() s.shutdownFn()
// wait for child routines // wait for child routines
if err := s.childRoutines.Wait(); err != nil && !xerrors.Is(err, context.Canceled) { if err := s.childRoutines.Wait(); err != nil && !errors.Is(err, context.Canceled) {
s.log.Error("Failed waiting for services to shutdown", "err", err) s.log.Error("Failed waiting for services to shutdown", "err", err)
} }
} }
......
...@@ -19,7 +19,6 @@ import ( ...@@ -19,7 +19,6 @@ import (
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util/errutil" "github.com/grafana/grafana/pkg/util/errutil"
"github.com/grafana/grafana/pkg/util/proxyutil" "github.com/grafana/grafana/pkg/util/proxyutil"
"golang.org/x/xerrors"
) )
var ( var (
...@@ -382,7 +381,7 @@ func restartKilledProcess(ctx context.Context, p Plugin) error { ...@@ -382,7 +381,7 @@ func restartKilledProcess(ctx context.Context, p Plugin) error {
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():
if err := ctx.Err(); err != nil && !xerrors.Is(err, context.Canceled) { if err := ctx.Err(); err != nil && !errors.Is(err, context.Canceled) {
return err return err
} }
return nil return nil
......
...@@ -21,7 +21,6 @@ import ( ...@@ -21,7 +21,6 @@ import (
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
"github.com/grafana/grafana/pkg/util/errutil" "github.com/grafana/grafana/pkg/util/errutil"
"golang.org/x/xerrors"
) )
var ( var (
...@@ -193,11 +192,11 @@ func (pm *PluginManager) scan(pluginDir string, requireSigned bool) error { ...@@ -193,11 +192,11 @@ func (pm *PluginManager) scan(pluginDir string, requireSigned bool) error {
} }
if err := util.Walk(pluginDir, true, true, scanner.walker); err != nil { if err := util.Walk(pluginDir, true, true, scanner.walker); err != nil {
if xerrors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
pm.log.Debug("Couldn't scan directory since it doesn't exist", "pluginDir", pluginDir) pm.log.Debug("Couldn't scan directory since it doesn't exist", "pluginDir", pluginDir)
return nil return nil
} }
if xerrors.Is(err, os.ErrPermission) { if errors.Is(err, os.ErrPermission) {
pm.log.Debug("Couldn't scan directory due to lack of permissions", "pluginDir", pluginDir) pm.log.Debug("Couldn't scan directory due to lack of permissions", "pluginDir", pluginDir)
return nil return nil
} }
......
...@@ -2,6 +2,7 @@ package alerting ...@@ -2,6 +2,7 @@ package alerting
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"time" "time"
...@@ -16,7 +17,6 @@ import ( ...@@ -16,7 +17,6 @@ import (
"github.com/grafana/grafana/pkg/services/rendering" "github.com/grafana/grafana/pkg/services/rendering"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
"golang.org/x/xerrors"
) )
// AlertEngine is the background process that // AlertEngine is the background process that
...@@ -215,9 +215,9 @@ func (e *AlertEngine) processJob(attemptID int, attemptChan chan int, cancelChan ...@@ -215,9 +215,9 @@ func (e *AlertEngine) processJob(attemptID int, attemptChan chan int, cancelChan
evalContext.Rule.State = evalContext.GetNewState() evalContext.Rule.State = evalContext.GetNewState()
if err := e.resultHandler.handle(evalContext); err != nil { if err := e.resultHandler.handle(evalContext); err != nil {
switch { switch {
case xerrors.Is(err, context.Canceled): case errors.Is(err, context.Canceled):
e.log.Debug("Result handler returned context.Canceled") e.log.Debug("Result handler returned context.Canceled")
case xerrors.Is(err, context.DeadlineExceeded): case errors.Is(err, context.DeadlineExceeded):
e.log.Debug("Result handler returned context.DeadlineExceeded") e.log.Debug("Result handler returned context.DeadlineExceeded")
default: default:
e.log.Error("Failed to handle result", "err", err) e.log.Error("Failed to handle result", "err", err)
......
...@@ -271,7 +271,7 @@ func TestAlertRuleExtraction(t *testing.T) { ...@@ -271,7 +271,7 @@ func TestAlertRuleExtraction(t *testing.T) {
Convey("Should fail on save", func() { Convey("Should fail on save", func() {
_, err := extractor.GetAlerts() _, err := extractor.GetAlerts()
So(err.Error(), ShouldEqual, "Alert validation error: Panel id is not correct, alertName=Influxdb, panelId=1") So(err.Error(), ShouldEqual, "alert validation error: Panel id is not correct, alertName=Influxdb, panelId=1")
}) })
}) })
}) })
......
...@@ -24,7 +24,7 @@ func TestSlackNotifier(t *testing.T) { ...@@ -24,7 +24,7 @@ func TestSlackNotifier(t *testing.T) {
} }
_, err = NewSlackNotifier(model) _, err = NewSlackNotifier(model)
So(err, ShouldBeError, "Alert validation error: Could not find url property in settings") So(err, ShouldBeError, "alert validation error: Could not find url property in settings")
}) })
//nolint:goconst //nolint:goconst
...@@ -157,7 +157,7 @@ func TestSlackNotifier(t *testing.T) { ...@@ -157,7 +157,7 @@ func TestSlackNotifier(t *testing.T) {
_, err = NewSlackNotifier(model) _, err = NewSlackNotifier(model)
So(err, ShouldBeError, "Alert validation error: Recipient on invalid format: \"#open tsdb\"") So(err, ShouldBeError, "alert validation error: Recipient on invalid format: \"#open tsdb\"")
}) })
Convey("with user recipient with spaces should return an error", func() { Convey("with user recipient with spaces should return an error", func() {
...@@ -177,7 +177,7 @@ func TestSlackNotifier(t *testing.T) { ...@@ -177,7 +177,7 @@ func TestSlackNotifier(t *testing.T) {
_, err = NewSlackNotifier(model) _, err = NewSlackNotifier(model)
So(err, ShouldBeError, "Alert validation error: Recipient on invalid format: \"@user name\"") So(err, ShouldBeError, "alert validation error: Recipient on invalid format: \"@user name\"")
}) })
Convey("with user recipient with uppercase letters should return an error", func() { Convey("with user recipient with uppercase letters should return an error", func() {
...@@ -197,7 +197,7 @@ func TestSlackNotifier(t *testing.T) { ...@@ -197,7 +197,7 @@ func TestSlackNotifier(t *testing.T) {
_, err = NewSlackNotifier(model) _, err = NewSlackNotifier(model)
So(err, ShouldBeError, "Alert validation error: Recipient on invalid format: \"@User\"") So(err, ShouldBeError, "alert validation error: Recipient on invalid format: \"@User\"")
}) })
Convey("with Slack ID for recipient should work", func() { Convey("with Slack ID for recipient should work", func() {
......
...@@ -2,6 +2,7 @@ package alerting ...@@ -2,6 +2,7 @@ package alerting
import ( import (
"context" "context"
"errors"
"time" "time"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
...@@ -9,7 +10,6 @@ import ( ...@@ -9,7 +10,6 @@ import (
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/metrics" "github.com/grafana/grafana/pkg/infra/metrics"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"golang.org/x/xerrors"
"github.com/grafana/grafana/pkg/services/annotations" "github.com/grafana/grafana/pkg/services/annotations"
"github.com/grafana/grafana/pkg/services/rendering" "github.com/grafana/grafana/pkg/services/rendering"
...@@ -101,9 +101,9 @@ func (handler *defaultResultHandler) handle(evalContext *EvalContext) error { ...@@ -101,9 +101,9 @@ func (handler *defaultResultHandler) handle(evalContext *EvalContext) error {
if err := handler.notifier.SendIfNeeded(evalContext); err != nil { if err := handler.notifier.SendIfNeeded(evalContext); err != nil {
switch { switch {
case xerrors.Is(err, context.Canceled): case errors.Is(err, context.Canceled):
handler.log.Debug("handler.notifier.SendIfNeeded returned context.Canceled") handler.log.Debug("handler.notifier.SendIfNeeded returned context.Canceled")
case xerrors.Is(err, context.DeadlineExceeded): case errors.Is(err, context.DeadlineExceeded):
handler.log.Debug("handler.notifier.SendIfNeeded returned context.DeadlineExceeded") handler.log.Debug("handler.notifier.SendIfNeeded returned context.DeadlineExceeded")
default: default:
handler.log.Error("handler.notifier.SendIfNeeded failed", "err", err) handler.log.Error("handler.notifier.SendIfNeeded failed", "err", err)
......
...@@ -66,10 +66,10 @@ func (e ValidationError) Error() string { ...@@ -66,10 +66,10 @@ func (e ValidationError) Error() string {
} }
if e.Err != nil { if e.Err != nil {
return fmt.Sprintf("Alert validation error: %s%s", e.Err.Error(), extraInfo) return fmt.Sprintf("alert validation error: %s%s", e.Err.Error(), extraInfo)
} }
return fmt.Sprintf("Alert validation error: %s", extraInfo) return fmt.Sprintf("alert validation error: %s", extraInfo)
} }
var ( var (
......
...@@ -215,7 +215,7 @@ func TestAlertRuleModel(t *testing.T) { ...@@ -215,7 +215,7 @@ func TestAlertRuleModel(t *testing.T) {
_, err := NewRuleFromDBAlert(alert) _, err := NewRuleFromDBAlert(alert)
So(err, ShouldNotBeNil) So(err, ShouldNotBeNil)
So(err.Error(), ShouldEqual, "Alert validation error: Neither id nor uid is specified in 'notifications' block, type assertion to string failed AlertId: 1 PanelId: 1 DashboardId: 1") So(err.Error(), ShouldEqual, "alert validation error: Neither id nor uid is specified in 'notifications' block, type assertion to string failed AlertId: 1 PanelId: 1 DashboardId: 1")
}) })
}) })
} }
package dashboards package dashboards
import ( import (
"fmt"
"testing" "testing"
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
...@@ -10,7 +11,6 @@ import ( ...@@ -10,7 +11,6 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/guardian"
. "github.com/smartystreets/goconvey/convey" . "github.com/smartystreets/goconvey/convey"
"golang.org/x/xerrors"
) )
func TestDashboardService(t *testing.T) { func TestDashboardService(t *testing.T) {
...@@ -145,12 +145,12 @@ func TestDashboardService(t *testing.T) { ...@@ -145,12 +145,12 @@ func TestDashboardService(t *testing.T) {
}) })
bus.AddHandler("test", func(cmd *models.ValidateDashboardAlertsCommand) error { bus.AddHandler("test", func(cmd *models.ValidateDashboardAlertsCommand) error {
return xerrors.New("Alert validation error") return fmt.Errorf("alert validation error")
}) })
dto.Dashboard = models.NewDashboard("Dash") dto.Dashboard = models.NewDashboard("Dash")
_, err := service.SaveDashboard(dto, false) _, err := service.SaveDashboard(dto, false)
So(err.Error(), ShouldEqual, "Alert validation error") So(err.Error(), ShouldEqual, "alert validation error")
}) })
}) })
......
...@@ -6,7 +6,6 @@ import ( ...@@ -6,7 +6,6 @@ import (
"sync" "sync"
"github.com/BurntSushi/toml" "github.com/BurntSushi/toml"
"golang.org/x/xerrors"
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
...@@ -136,7 +135,7 @@ func readConfig(configFile string) (*Config, error) { ...@@ -136,7 +135,7 @@ func readConfig(configFile string) (*Config, error) {
} }
if len(result.Servers) == 0 { if len(result.Servers) == 0 {
return nil, xerrors.New("LDAP enabled but no LDAP servers defined in config file") return nil, fmt.Errorf("LDAP enabled but no LDAP servers defined in config file")
} }
// set default org id // set default org id
...@@ -164,11 +163,11 @@ func assertNotEmptyCfg(val interface{}, propName string) error { ...@@ -164,11 +163,11 @@ func assertNotEmptyCfg(val interface{}, propName string) error {
switch v := val.(type) { switch v := val.(type) {
case string: case string:
if v == "" { if v == "" {
return xerrors.Errorf("LDAP config file is missing option: %v", propName) return fmt.Errorf("LDAP config file is missing option: %q", propName)
} }
case []string: case []string:
if len(v) == 0 { if len(v) == 0 {
return xerrors.Errorf("LDAP config file is missing option: %v", propName) return fmt.Errorf("LDAP config file is missing option: %q", propName)
} }
default: default:
fmt.Println("unknown") fmt.Println("unknown")
......
...@@ -321,7 +321,7 @@ func TestNotificationAsConfig(t *testing.T) { ...@@ -321,7 +321,7 @@ func TestNotificationAsConfig(t *testing.T) {
cfgProvider := &configReader{log: log.New("test logger")} cfgProvider := &configReader{log: log.New("test logger")}
_, err := cfgProvider.readConfig(incorrectSettings) _, err := cfgProvider.readConfig(incorrectSettings)
So(err, ShouldNotBeNil) So(err, ShouldNotBeNil)
So(err.Error(), ShouldEqual, "Alert validation error: Could not find url property in settings") So(err.Error(), ShouldEqual, "alert validation error: Could not find url property in settings")
}) })
}) })
} }
...@@ -2,23 +2,18 @@ package errutil ...@@ -2,23 +2,18 @@ package errutil
import ( import (
"fmt" "fmt"
"golang.org/x/xerrors"
) )
// Wrap is a simple wrapper around Errorf that is doing error wrapping. You can read how that works in // Wrap is a simple wrapper around fmt.Errorf that wraps errors.
// https://godoc.org/golang.org/x/xerrors#Errorf but its API is very implicit which is a reason for this wrapper.
// There is also a discussion (https://github.com/golang/go/issues/29934) where many comments make arguments for such
// wrapper so hopefully it will be added in the standard lib later.
func Wrap(message string, err error) error { func Wrap(message string, err error) error {
if err == nil { if err == nil {
return nil return nil
} }
return xerrors.Errorf("%v: %w", message, err) return fmt.Errorf("%v: %w", message, err)
} }
// Wrapf is a simple wrapper around Errorf that is doing error wrapping // Wrapf is a simple wrapper around fmt.Errorf that wraps errors.
// Wrapf allows you to send a format and args instead of just a message. // Wrapf allows you to send a format and args instead of just a message.
func Wrapf(err error, message string, a ...interface{}) error { func Wrapf(err error, message string, a ...interface{}) error {
if err == nil { if err == nil {
......
...@@ -12,7 +12,7 @@ import ( ...@@ -12,7 +12,7 @@ import (
func ParseIPAddress(input string) (string, error) { func ParseIPAddress(input string) (string, error) {
addr, err := SplitHostPort(input) addr, err := SplitHostPort(input)
if err != nil { if err != nil {
return "", errutil.Wrapf(err, "Failed to split network address '%s' by host and port", return "", errutil.Wrapf(err, "failed to split network address %q by host and port",
input) input)
} }
......
package util package util
import ( import (
"fmt"
"testing" "testing"
. "github.com/smartystreets/goconvey/convey" . "github.com/smartystreets/goconvey/convey"
"golang.org/x/xerrors"
) )
func TestParseIPAddress(t *testing.T) { func TestParseIPAddress(t *testing.T) {
...@@ -28,16 +28,16 @@ func TestParseIPAddress(t *testing.T) { ...@@ -28,16 +28,16 @@ func TestParseIPAddress(t *testing.T) {
Convey("Invalid address", t, func() { Convey("Invalid address", t, func() {
_, err := ParseIPAddress("[::1") _, err := ParseIPAddress("[::1")
So(err, ShouldBeError, xerrors.Errorf( So(err, ShouldBeError, fmt.Errorf(
"Failed to split network address '[::1' by host and port: Malformed IPv6 address: '[::1'")) `failed to split network address "[::1" by host and port: Malformed IPv6 address: '[::1'`))
_, err = ParseIPAddress("::1]") _, err = ParseIPAddress("::1]")
So(err, ShouldBeError, xerrors.Errorf( So(err, ShouldBeError, fmt.Errorf(
"Failed to split network address '::1]' by host and port: net.SplitHostPort failed for '::1]': address ::1]: too many colons in address")) `failed to split network address "::1]" by host and port: net.SplitHostPort failed for '::1]': address ::1]: too many colons in address`))
_, err = ParseIPAddress("") _, err = ParseIPAddress("")
So(err, ShouldBeError, xerrors.Errorf( So(err, ShouldBeError, fmt.Errorf(
"Failed to split network address '' by host and port: Input is empty")) `failed to split network address "" by host and port: Input is empty`))
}) })
Convey("Loopback address", t, func() { Convey("Loopback address", t, func() {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment