From 4114515fa0368c4afde831697e351820bb1ab039 Mon Sep 17 00:00:00 2001 From: Oleksandr Redko Date: Wed, 29 May 2024 18:10:04 +0300 Subject: [PATCH] refactor: use errors.New instead of fmt.Errorf (#3112) --- .golangci.yml | 7 +++++++ _examples/dataloader/resolvers.go | 3 ++- _examples/scalars/model/model.go | 8 ++++---- _examples/todo/todo.go | 5 ++--- client/websocket.go | 3 ++- codegen/config/binder.go | 4 ++-- codegen/config/config.go | 5 +++-- codegen/config/exec.go | 9 +++++---- codegen/config/package.go | 8 ++++---- codegen/config/resolver.go | 3 ++- codegen/data.go | 7 ++++--- codegen/field.go | 2 +- codegen/generate.go | 2 +- codegen/templates/import.go | 5 +++-- codegen/templates/templates.go | 5 +++-- .../testserver/followschema/directive_test.go | 17 +++++++++-------- .../testserver/followschema/interfaces_test.go | 4 ++-- codegen/testserver/followschema/models.go | 6 +++--- .../followschema/mutation_with_custom_scalar.go | 6 +++--- codegen/testserver/singlefile/directive_test.go | 17 +++++++++-------- .../testserver/singlefile/interfaces_test.go | 4 ++-- codegen/testserver/singlefile/models.go | 6 +++--- .../singlefile/mutation_with_custom_scalar.go | 6 +++--- graphql/duration.go | 4 ++-- graphql/executor/extensions.go | 9 +++++---- graphql/executor/testexecutor/testexecutor.go | 3 ++- graphql/float.go | 3 ++- .../apollofederatedtracingv1/tree_builder.go | 13 +++++++------ graphql/handler/extension/apq.go | 4 ++-- graphql/handler/extension/complexity.go | 4 ++-- graphql/handler/server.go | 7 ++++--- graphql/handler/server_test.go | 4 ++-- graphql/handler/testserver/testserver.go | 3 ++- integration/server/resolver.go | 9 +++++---- internal/code/compare.go | 5 +++-- main.go | 8 ++++---- plugin/resolvergen/resolver.go | 2 +- 37 files changed, 122 insertions(+), 98 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index f741cca531..b404d47ad3 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -8,6 +8,12 @@ linters-settings: - (io.Writer).Write - io.Copy - io.WriteString + perfsprint: + int-conversion: false + err-error: false + errorf: true + sprintf1: false + strconcat: false revive: enable-all-rules: false rules: @@ -45,6 +51,7 @@ linters: - ineffassign - misspell - nakedret + - perfsprint - prealloc - revive - staticcheck diff --git a/_examples/dataloader/resolvers.go b/_examples/dataloader/resolvers.go index 759f88c114..eaec65cdd7 100644 --- a/_examples/dataloader/resolvers.go +++ b/_examples/dataloader/resolvers.go @@ -6,6 +6,7 @@ import ( "context" "fmt" "math/rand" + "strconv" "time" ) @@ -70,7 +71,7 @@ func (r *queryResolver) Customers(ctx context.Context) ([]*Customer, error) { func (r *queryResolver) Torture1d(ctx context.Context, customerIds []int) ([]*Customer, error) { result := make([]*Customer, len(customerIds)) for i, id := range customerIds { - result[i] = &Customer{ID: id, Name: fmt.Sprintf("%d", i), AddressID: rand.Int() % 10} + result[i] = &Customer{ID: id, Name: strconv.Itoa(i), AddressID: rand.Int() % 10} } return result, nil } diff --git a/_examples/scalars/model/model.go b/_examples/scalars/model/model.go index 48c5a25bcd..c33791adf2 100644 --- a/_examples/scalars/model/model.go +++ b/_examples/scalars/model/model.go @@ -56,13 +56,13 @@ type Point struct { func (p *Point) UnmarshalGQL(v any) error { pointStr, ok := v.(string) if !ok { - return fmt.Errorf("points must be strings") + return errors.New("points must be strings") } parts := strings.Split(pointStr, ",") if len(parts) != 2 { - return fmt.Errorf("points must have 2 parts") + return errors.New("points must have 2 parts") } var err error @@ -108,7 +108,7 @@ func MarshalID(id external.ObjectID) graphql.Marshaler { func UnmarshalID(v any) (external.ObjectID, error) { str, ok := v.(string) if !ok { - return 0, fmt.Errorf("ids must be strings") + return 0, errors.New("ids must be strings") } i, err := strconv.Atoi(str[1 : len(str)-1]) return external.ObjectID(i), err @@ -166,7 +166,7 @@ func (e Tier) String() string { func (e *Tier) UnmarshalGQL(v any) error { str, ok := v.(string) if !ok { - return fmt.Errorf("enums must be strings") + return errors.New("enums must be strings") } var err error diff --git a/_examples/todo/todo.go b/_examples/todo/todo.go index 128d7c48d0..5224f63251 100644 --- a/_examples/todo/todo.go +++ b/_examples/todo/todo.go @@ -5,7 +5,6 @@ package todo import ( "context" "errors" - "fmt" "time" "github.com/mitchellh/mapstructure" @@ -47,11 +46,11 @@ func New() Config { case RoleOwner: ownable, isOwnable := obj.(Ownable) if !isOwnable { - return nil, fmt.Errorf("obj cant be owned") + return nil, errors.New("obj cant be owned") } if ownable.Owner().ID != getUserId(ctx) { - return nil, fmt.Errorf("you don't own that") + return nil, errors.New("you don't own that") } } diff --git a/client/websocket.go b/client/websocket.go index 0b81f5a1c4..6a14f7fead 100644 --- a/client/websocket.go +++ b/client/websocket.go @@ -2,6 +2,7 @@ package client import ( "encoding/json" + "errors" "fmt" "io" "net/http/httptest" @@ -127,7 +128,7 @@ func (p *Client) WebsocketWithPayload(query string, initPayload map[string]any, case connectionKaMsg: continue case errorMsg: - return fmt.Errorf(string(op.Payload)) + return errors.New(string(op.Payload)) default: return fmt.Errorf("expected data message, got %#v", op) } diff --git a/codegen/config/binder.go b/codegen/config/binder.go index 6a4880325c..b5b5b3c756 100644 --- a/codegen/config/binder.go +++ b/codegen/config/binder.go @@ -99,7 +99,7 @@ var ( func (b *Binder) DefaultUserObject(name string) (types.Type, error) { models := b.cfg.Models[name].Model if len(models) == 0 { - return nil, fmt.Errorf(name + " not found in typemap") + return nil, fmt.Errorf("%s not found in typemap", name) } if models[0] == "map[string]interface{}" { @@ -125,7 +125,7 @@ func (b *Binder) DefaultUserObject(name string) (types.Type, error) { func (b *Binder) FindObject(pkgName string, typeName string) (types.Object, error) { if pkgName == "" { - return nil, fmt.Errorf("package cannot be nil") + return nil, errors.New("package cannot be nil") } pkg := b.pkgs.LoadWithTypes(pkgName) diff --git a/codegen/config/config.go b/codegen/config/config.go index 4c8cd76293..035436fff8 100644 --- a/codegen/config/config.go +++ b/codegen/config/config.go @@ -2,6 +2,7 @@ package config import ( "bytes" + "errors" "fmt" "go/types" "io" @@ -564,11 +565,11 @@ func (c *Config) check() error { Declaree: "federation", }) if c.Federation.ImportPath() != c.Exec.ImportPath() { - return fmt.Errorf("federation and exec must be in the same package") + return errors.New("federation and exec must be in the same package") } } if c.Federated { - return fmt.Errorf("federated has been removed, instead use\nfederation:\n filename: path/to/federated.go") + return errors.New("federated has been removed, instead use\nfederation:\n filename: path/to/federated.go") } for importPath, pkg := range fileList { diff --git a/codegen/config/exec.go b/codegen/config/exec.go index fe1dccd21d..838e17b2c2 100644 --- a/codegen/config/exec.go +++ b/codegen/config/exec.go @@ -1,6 +1,7 @@ package config import ( + "errors" "fmt" "go/types" "path/filepath" @@ -38,15 +39,15 @@ func (r *ExecConfig) Check() error { switch r.Layout { case ExecLayoutSingleFile: if r.Filename == "" { - return fmt.Errorf("filename must be specified when using single-file layout") + return errors.New("filename must be specified when using single-file layout") } if !strings.HasSuffix(r.Filename, ".go") { - return fmt.Errorf("filename should be path to a go source file when using single-file layout") + return errors.New("filename should be path to a go source file when using single-file layout") } r.Filename = abs(r.Filename) case ExecLayoutFollowSchema: if r.DirName == "" { - return fmt.Errorf("dir must be specified when using follow-schema layout") + return errors.New("dir must be specified when using follow-schema layout") } r.DirName = abs(r.DirName) default: @@ -54,7 +55,7 @@ func (r *ExecConfig) Check() error { } if strings.ContainsAny(r.Package, "./\\") { - return fmt.Errorf("package should be the output package name only, do not include the output filename") + return errors.New("package should be the output package name only, do not include the output filename") } if r.Package == "" && r.Dir() != "" { diff --git a/codegen/config/package.go b/codegen/config/package.go index 05e178b401..a399b2cc04 100644 --- a/codegen/config/package.go +++ b/codegen/config/package.go @@ -1,7 +1,7 @@ package config import ( - "fmt" + "errors" "go/types" "path/filepath" "strings" @@ -44,13 +44,13 @@ func (c *PackageConfig) IsDefined() bool { func (c *PackageConfig) Check() error { if strings.ContainsAny(c.Package, "./\\") { - return fmt.Errorf("package should be the output package name only, do not include the output filename") + return errors.New("package should be the output package name only, do not include the output filename") } if c.Filename == "" { - return fmt.Errorf("filename must be specified") + return errors.New("filename must be specified") } if !strings.HasSuffix(c.Filename, ".go") { - return fmt.Errorf("filename should be path to a go source file") + return errors.New("filename should be path to a go source file") } c.Filename = abs(c.Filename) diff --git a/codegen/config/resolver.go b/codegen/config/resolver.go index cb5fb72b36..1901fd2d35 100644 --- a/codegen/config/resolver.go +++ b/codegen/config/resolver.go @@ -1,6 +1,7 @@ package config import ( + "errors" "fmt" "go/types" "path/filepath" @@ -59,7 +60,7 @@ func (r *ResolverConfig) Check() error { } if strings.ContainsAny(r.Package, "./\\") { - return fmt.Errorf("package should be the output package name only, do not include the output filename") + return errors.New("package should be the output package name only, do not include the output filename") } if r.Package == "" && r.Dir() != "" { diff --git a/codegen/data.go b/codegen/data.go index 3b3e346aac..7110de2f92 100644 --- a/codegen/data.go +++ b/codegen/data.go @@ -1,6 +1,7 @@ package codegen import ( + "errors" "fmt" "os" "path/filepath" @@ -137,7 +138,7 @@ func BuildData(cfg *config.Config, plugins ...any) (*Data, error) { if s.Schema.Query != nil { s.QueryRoot = s.Objects.ByName(s.Schema.Query.Name) } else { - return nil, fmt.Errorf("query entry point missing") + return nil, errors.New("query entry point missing") } if s.Schema.Mutation != nil { @@ -170,7 +171,7 @@ func BuildData(cfg *config.Config, plugins ...any) (*Data, error) { } // otherwise show a generic error message - return nil, fmt.Errorf("invalid types were encountered while traversing the go source code, this probably means the invalid code generated isnt correct. add try adding -v to debug") + return nil, errors.New("invalid types were encountered while traversing the go source code, this probably means the invalid code generated isnt correct. add try adding -v to debug") } aSources := []AugmentedSource{} for _, s := range cfg.Sources { @@ -204,7 +205,7 @@ func BuildData(cfg *config.Config, plugins ...any) (*Data, error) { func (b *builder) injectIntrospectionRoots(s *Data) error { obj := s.Objects.ByName(b.Schema.Query.Name) if obj == nil { - return fmt.Errorf("root query type must be defined") + return errors.New("root query type must be defined") } __type, err := b.buildField(obj, &ast.FieldDefinition{ diff --git a/codegen/field.go b/codegen/field.go index bfcf3c5dba..509f48cdcc 100644 --- a/codegen/field.go +++ b/codegen/field.go @@ -174,7 +174,7 @@ func (b *builder) bindField(obj *Object, f *Field) (errret error) { } else if s := sig.Results(); s.Len() == 2 && s.At(1).Type().String() == "bool" { f.VOkFunc = true } else if sig.Results().Len() != 2 { - return fmt.Errorf("method has wrong number of args") + return errors.New("method has wrong number of args") } params := sig.Params() // If the first argument is the context, remove it from the comparison and set diff --git a/codegen/generate.go b/codegen/generate.go index d63758abf1..bbd4d9472e 100644 --- a/codegen/generate.go +++ b/codegen/generate.go @@ -20,7 +20,7 @@ var codegenTemplates embed.FS func GenerateCode(data *Data) error { if !data.Config.Exec.IsDefined() { - return fmt.Errorf("missing exec config") + return errors.New("missing exec config") } switch data.Config.Exec.Layout { diff --git a/codegen/templates/import.go b/codegen/templates/import.go index 50115283fb..c26bdeab7f 100644 --- a/codegen/templates/import.go +++ b/codegen/templates/import.go @@ -1,6 +1,7 @@ package templates import ( + "errors" "fmt" "go/types" "strconv" @@ -62,11 +63,11 @@ func (s *Imports) Reserve(path string, aliases ...string) (string, error) { if existing.Alias == alias { return "", nil } - return "", fmt.Errorf("ambient import already exists") + return "", errors.New("ambient import already exists") } if alias := s.findByAlias(alias); alias != nil { - return "", fmt.Errorf("ambient import collides on an alias") + return "", errors.New("ambient import collides on an alias") } s.imports = append(s.imports, &Import{ diff --git a/codegen/templates/templates.go b/codegen/templates/templates.go index f2c367cb3b..010916cd50 100644 --- a/codegen/templates/templates.go +++ b/codegen/templates/templates.go @@ -2,6 +2,7 @@ package templates import ( "bytes" + "errors" "fmt" "go/types" "io/fs" @@ -71,7 +72,7 @@ var ( // files inside the directory where you wrote the plugin. func Render(cfg Options) error { if CurrentImports != nil { - panic(fmt.Errorf("recursive or concurrent call to RenderToFile detected")) + panic(errors.New("recursive or concurrent call to RenderToFile detected")) } CurrentImports = &Imports{packages: cfg.Packages, destDir: filepath.Dir(cfg.Filename)} @@ -591,7 +592,7 @@ func Dump(val any) string { case int: return strconv.Itoa(val) case int64: - return fmt.Sprintf("%d", val) + return strconv.FormatInt(val, 10) case float64: return fmt.Sprintf("%f", val) case string: diff --git a/codegen/testserver/followschema/directive_test.go b/codegen/testserver/followschema/directive_test.go index f468e01174..92f13c4afc 100644 --- a/codegen/testserver/followschema/directive_test.go +++ b/codegen/testserver/followschema/directive_test.go @@ -2,6 +2,7 @@ package followschema import ( "context" + "errors" "fmt" "testing" @@ -94,9 +95,9 @@ func TestDirectives(t *testing.T) { Length: func(ctx context.Context, obj any, next graphql.Resolver, min int, max *int, message *string) (any, error) { e := func(msg string) error { if message == nil { - return fmt.Errorf(msg) + return errors.New(msg) } - return fmt.Errorf(*message) + return errors.New(*message) } res, err := next(ctx) if err != nil { @@ -121,28 +122,28 @@ func TestDirectives(t *testing.T) { switch res := res.(type) { case int: if min != nil && res < *min { - return nil, fmt.Errorf("too small") + return nil, errors.New("too small") } if max != nil && res > *max { - return nil, fmt.Errorf("too large") + return nil, errors.New("too large") } return next(ctx) case int64: if min != nil && int(res) < *min { - return nil, fmt.Errorf("too small") + return nil, errors.New("too small") } if max != nil && int(res) > *max { - return nil, fmt.Errorf("too large") + return nil, errors.New("too large") } return next(ctx) case *int: if min != nil && *res < *min { - return nil, fmt.Errorf("too small") + return nil, errors.New("too small") } if max != nil && *res > *max { - return nil, fmt.Errorf("too large") + return nil, errors.New("too large") } return next(ctx) } diff --git a/codegen/testserver/followschema/interfaces_test.go b/codegen/testserver/followschema/interfaces_test.go index 80c06c106a..6111b8a051 100644 --- a/codegen/testserver/followschema/interfaces_test.go +++ b/codegen/testserver/followschema/interfaces_test.go @@ -2,7 +2,7 @@ package followschema import ( "context" - "fmt" + "errors" "reflect" "testing" @@ -163,7 +163,7 @@ func TestInterfaces(t *testing.T) { resolvers.QueryResolver.NotAnInterface = func(ctx context.Context) (byInterface BackedByInterface, err error) { return &BackedByInterfaceImpl{ Value: "A", - Error: fmt.Errorf("boom"), + Error: errors.New("boom"), }, nil } diff --git a/codegen/testserver/followschema/models.go b/codegen/testserver/followschema/models.go index e73bdcad86..13edc613a5 100644 --- a/codegen/testserver/followschema/models.go +++ b/codegen/testserver/followschema/models.go @@ -2,7 +2,7 @@ package followschema import ( "context" - "fmt" + "errors" "io" ) @@ -27,11 +27,11 @@ type Error struct { } func (Error) ErrorOnRequiredField() (string, error) { - return "", fmt.Errorf("boom") + return "", errors.New("boom") } func (Error) ErrorOnNonRequiredField() (string, error) { - return "", fmt.Errorf("boom") + return "", errors.New("boom") } func (Error) NilOnRequiredField() *string { diff --git a/codegen/testserver/followschema/mutation_with_custom_scalar.go b/codegen/testserver/followschema/mutation_with_custom_scalar.go index 219ae732ff..5683ad3d03 100644 --- a/codegen/testserver/followschema/mutation_with_custom_scalar.go +++ b/codegen/testserver/followschema/mutation_with_custom_scalar.go @@ -2,7 +2,7 @@ package followschema import ( "encoding/json" - "fmt" + "errors" "io" "regexp" ) @@ -14,10 +14,10 @@ type Email string func (value *Email) UnmarshalGQL(v any) error { input, ok := v.(string) if !ok { - return fmt.Errorf("email expects a string value") + return errors.New("email expects a string value") } if !re.MatchString(input) { - return fmt.Errorf("invalid email format") + return errors.New("invalid email format") } *value = Email(input) return nil diff --git a/codegen/testserver/singlefile/directive_test.go b/codegen/testserver/singlefile/directive_test.go index 5c90d41e2f..eaa0c54c21 100644 --- a/codegen/testserver/singlefile/directive_test.go +++ b/codegen/testserver/singlefile/directive_test.go @@ -2,6 +2,7 @@ package singlefile import ( "context" + "errors" "fmt" "testing" @@ -94,9 +95,9 @@ func TestDirectives(t *testing.T) { Length: func(ctx context.Context, obj any, next graphql.Resolver, min int, max *int, message *string) (any, error) { e := func(msg string) error { if message == nil { - return fmt.Errorf(msg) + return errors.New(msg) } - return fmt.Errorf(*message) + return errors.New(*message) } res, err := next(ctx) if err != nil { @@ -121,28 +122,28 @@ func TestDirectives(t *testing.T) { switch res := res.(type) { case int: if min != nil && res < *min { - return nil, fmt.Errorf("too small") + return nil, errors.New("too small") } if max != nil && res > *max { - return nil, fmt.Errorf("too large") + return nil, errors.New("too large") } return next(ctx) case int64: if min != nil && int(res) < *min { - return nil, fmt.Errorf("too small") + return nil, errors.New("too small") } if max != nil && int(res) > *max { - return nil, fmt.Errorf("too large") + return nil, errors.New("too large") } return next(ctx) case *int: if min != nil && *res < *min { - return nil, fmt.Errorf("too small") + return nil, errors.New("too small") } if max != nil && *res > *max { - return nil, fmt.Errorf("too large") + return nil, errors.New("too large") } return next(ctx) } diff --git a/codegen/testserver/singlefile/interfaces_test.go b/codegen/testserver/singlefile/interfaces_test.go index 6151769c88..e14b100468 100644 --- a/codegen/testserver/singlefile/interfaces_test.go +++ b/codegen/testserver/singlefile/interfaces_test.go @@ -2,7 +2,7 @@ package singlefile import ( "context" - "fmt" + "errors" "reflect" "testing" @@ -163,7 +163,7 @@ func TestInterfaces(t *testing.T) { resolvers.QueryResolver.NotAnInterface = func(ctx context.Context) (byInterface BackedByInterface, err error) { return &BackedByInterfaceImpl{ Value: "A", - Error: fmt.Errorf("boom"), + Error: errors.New("boom"), }, nil } diff --git a/codegen/testserver/singlefile/models.go b/codegen/testserver/singlefile/models.go index f078cc36cd..e2abc8be8a 100644 --- a/codegen/testserver/singlefile/models.go +++ b/codegen/testserver/singlefile/models.go @@ -2,7 +2,7 @@ package singlefile import ( "context" - "fmt" + "errors" "io" ) @@ -27,11 +27,11 @@ type Error struct { } func (Error) ErrorOnRequiredField() (string, error) { - return "", fmt.Errorf("boom") + return "", errors.New("boom") } func (Error) ErrorOnNonRequiredField() (string, error) { - return "", fmt.Errorf("boom") + return "", errors.New("boom") } func (Error) NilOnRequiredField() *string { diff --git a/codegen/testserver/singlefile/mutation_with_custom_scalar.go b/codegen/testserver/singlefile/mutation_with_custom_scalar.go index 5cd618a60b..ee5ea57817 100644 --- a/codegen/testserver/singlefile/mutation_with_custom_scalar.go +++ b/codegen/testserver/singlefile/mutation_with_custom_scalar.go @@ -2,7 +2,7 @@ package singlefile import ( "encoding/json" - "fmt" + "errors" "io" "regexp" ) @@ -14,10 +14,10 @@ type Email string func (value *Email) UnmarshalGQL(v any) error { input, ok := v.(string) if !ok { - return fmt.Errorf("email expects a string value") + return errors.New("email expects a string value") } if !re.MatchString(input) { - return fmt.Errorf("invalid email format") + return errors.New("invalid email format") } *value = Email(input) return nil diff --git a/graphql/duration.go b/graphql/duration.go index 57ec53a0ca..bf2b564776 100644 --- a/graphql/duration.go +++ b/graphql/duration.go @@ -1,7 +1,7 @@ package graphql import ( - "fmt" + "errors" "time" dur "github.com/sosodev/duration" @@ -11,7 +11,7 @@ import ( func UnmarshalDuration(v any) (time.Duration, error) { input, ok := v.(string) if !ok { - return 0, fmt.Errorf("input must be a string") + return 0, errors.New("input must be a string") } d2, err := dur.Parse(input) diff --git a/graphql/executor/extensions.go b/graphql/executor/extensions.go index 56985aad30..758d8e4ec8 100644 --- a/graphql/executor/extensions.go +++ b/graphql/executor/extensions.go @@ -2,6 +2,7 @@ package executor import ( "context" + "errors" "fmt" "github.com/99designs/gqlgen/graphql" @@ -134,7 +135,7 @@ func (r aroundOpFunc) ExtensionName() string { func (r aroundOpFunc) Validate(schema graphql.ExecutableSchema) error { if r == nil { - return fmt.Errorf("OperationFunc can not be nil") + return errors.New("OperationFunc can not be nil") } return nil } @@ -151,7 +152,7 @@ func (r aroundRespFunc) ExtensionName() string { func (r aroundRespFunc) Validate(schema graphql.ExecutableSchema) error { if r == nil { - return fmt.Errorf("ResponseFunc can not be nil") + return errors.New("ResponseFunc can not be nil") } return nil } @@ -168,7 +169,7 @@ func (f aroundFieldFunc) ExtensionName() string { func (f aroundFieldFunc) Validate(schema graphql.ExecutableSchema) error { if f == nil { - return fmt.Errorf("FieldFunc can not be nil") + return errors.New("FieldFunc can not be nil") } return nil } @@ -185,7 +186,7 @@ func (f aroundRootFieldFunc) ExtensionName() string { func (f aroundRootFieldFunc) Validate(schema graphql.ExecutableSchema) error { if f == nil { - return fmt.Errorf("RootFieldFunc can not be nil") + return errors.New("RootFieldFunc can not be nil") } return nil } diff --git a/graphql/executor/testexecutor/testexecutor.go b/graphql/executor/testexecutor/testexecutor.go index 401e6df179..55778a22f1 100644 --- a/graphql/executor/testexecutor/testexecutor.go +++ b/graphql/executor/testexecutor/testexecutor.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "time" @@ -152,7 +153,7 @@ func NewError() *TestExecutor { } ran = true - graphql.AddError(ctx, fmt.Errorf("resolver error")) + graphql.AddError(ctx, errors.New("resolver error")) return &graphql.Response{ Data: []byte(`null`), diff --git a/graphql/float.go b/graphql/float.go index 7d447a4d25..067c4c27cb 100644 --- a/graphql/float.go +++ b/graphql/float.go @@ -3,6 +3,7 @@ package graphql import ( "context" "encoding/json" + "errors" "fmt" "io" "math" @@ -35,7 +36,7 @@ func UnmarshalFloat(v any) (float64, error) { func MarshalFloatContext(f float64) ContextMarshaler { return ContextWriterFunc(func(ctx context.Context, w io.Writer) error { if math.IsInf(f, 0) || math.IsNaN(f) { - return fmt.Errorf("cannot marshal infinite no NaN float values") + return errors.New("cannot marshal infinite no NaN float values") } io.WriteString(w, fmt.Sprintf("%g", f)) return nil diff --git a/graphql/handler/apollofederatedtracingv1/tree_builder.go b/graphql/handler/apollofederatedtracingv1/tree_builder.go index e211e626c0..8953ae1238 100644 --- a/graphql/handler/apollofederatedtracingv1/tree_builder.go +++ b/graphql/handler/apollofederatedtracingv1/tree_builder.go @@ -2,6 +2,7 @@ package apollofederatedtracingv1 import ( "context" + "errors" "fmt" "sync" "time" @@ -47,10 +48,10 @@ func NewTreeBuilder() *TreeBuilder { // StartTimer marks the time using protobuf timestamp format for use in timing calculations func (tb *TreeBuilder) StartTimer(ctx context.Context) { if tb.startTime != nil { - fmt.Println(fmt.Errorf("StartTimer called twice")) + fmt.Println(errors.New("StartTimer called twice")) } if tb.stopped { - fmt.Println(fmt.Errorf("StartTimer called after StopTimer")) + fmt.Println(errors.New("StartTimer called after StopTimer")) } rc := graphql.GetOperationContext(ctx) @@ -63,10 +64,10 @@ func (tb *TreeBuilder) StartTimer(ctx context.Context) { // StopTimer marks the end of the timer, along with setting the related fields in the protobuf representation func (tb *TreeBuilder) StopTimer(ctx context.Context) { if tb.startTime == nil { - fmt.Println(fmt.Errorf("StopTimer called before StartTimer")) + fmt.Println(errors.New("StopTimer called before StartTimer")) } if tb.stopped { - fmt.Println(fmt.Errorf("StopTimer called twice")) + fmt.Println(errors.New("StopTimer called twice")) } ts := graphql.Now().UTC() @@ -79,11 +80,11 @@ func (tb *TreeBuilder) StopTimer(ctx context.Context) { // field as now - tree.StartTime; these are used by Apollo to calculate how fields are being resolved in the AST func (tb *TreeBuilder) WillResolveField(ctx context.Context) { if tb.startTime == nil { - fmt.Println(fmt.Errorf("WillResolveField called before StartTimer")) + fmt.Println(errors.New("WillResolveField called before StartTimer")) return } if tb.stopped { - fmt.Println(fmt.Errorf("WillResolveField called after StopTimer")) + fmt.Println(errors.New("WillResolveField called after StopTimer")) return } fc := graphql.GetFieldContext(ctx) diff --git a/graphql/handler/extension/apq.go b/graphql/handler/extension/apq.go index 465c2ada61..115aaa8a46 100644 --- a/graphql/handler/extension/apq.go +++ b/graphql/handler/extension/apq.go @@ -4,7 +4,7 @@ import ( "context" "crypto/sha256" "encoding/hex" - "fmt" + "errors" "github.com/mitchellh/mapstructure" "github.com/vektah/gqlparser/v2/gqlerror" @@ -47,7 +47,7 @@ func (a AutomaticPersistedQuery) ExtensionName() string { func (a AutomaticPersistedQuery) Validate(schema graphql.ExecutableSchema) error { if a.Cache == nil { - return fmt.Errorf("AutomaticPersistedQuery.Cache can not be nil") + return errors.New("AutomaticPersistedQuery.Cache can not be nil") } return nil } diff --git a/graphql/handler/extension/complexity.go b/graphql/handler/extension/complexity.go index a5b6a60409..af1e002fc1 100644 --- a/graphql/handler/extension/complexity.go +++ b/graphql/handler/extension/complexity.go @@ -2,7 +2,7 @@ package extension import ( "context" - "fmt" + "errors" "github.com/vektah/gqlparser/v2/gqlerror" @@ -52,7 +52,7 @@ func (c ComplexityLimit) ExtensionName() string { func (c *ComplexityLimit) Validate(schema graphql.ExecutableSchema) error { if c.Func == nil { - return fmt.Errorf("ComplexityLimit func can not be nil") + return errors.New("ComplexityLimit func can not be nil") } c.es = schema return nil diff --git a/graphql/handler/server.go b/graphql/handler/server.go index 2114ff9283..e5c022a349 100644 --- a/graphql/handler/server.go +++ b/graphql/handler/server.go @@ -3,6 +3,7 @@ package handler import ( "context" "encoding/json" + "errors" "fmt" "net/http" "time" @@ -143,7 +144,7 @@ func (r OperationFunc) ExtensionName() string { func (r OperationFunc) Validate(schema graphql.ExecutableSchema) error { if r == nil { - return fmt.Errorf("OperationFunc can not be nil") + return errors.New("OperationFunc can not be nil") } return nil } @@ -160,7 +161,7 @@ func (r ResponseFunc) ExtensionName() string { func (r ResponseFunc) Validate(schema graphql.ExecutableSchema) error { if r == nil { - return fmt.Errorf("ResponseFunc can not be nil") + return errors.New("ResponseFunc can not be nil") } return nil } @@ -177,7 +178,7 @@ func (f FieldFunc) ExtensionName() string { func (f FieldFunc) Validate(schema graphql.ExecutableSchema) error { if f == nil { - return fmt.Errorf("FieldFunc can not be nil") + return errors.New("FieldFunc can not be nil") } return nil } diff --git a/graphql/handler/server_test.go b/graphql/handler/server_test.go index 6e40c92d87..541595add0 100644 --- a/graphql/handler/server_test.go +++ b/graphql/handler/server_test.go @@ -2,7 +2,7 @@ package handler_test import ( "context" - "fmt" + "errors" "net/http" "net/http/httptest" "net/url" @@ -171,7 +171,7 @@ func (t panicTransport) Supports(r *http.Request) bool { } func (t panicTransport) Do(w http.ResponseWriter, r *http.Request, exec graphql.GraphExecutor) { - panic(fmt.Errorf("panic in transport")) + panic(errors.New("panic in transport")) } func TestRecover(t *testing.T) { diff --git a/graphql/handler/testserver/testserver.go b/graphql/handler/testserver/testserver.go index a196191abf..33713b26d5 100644 --- a/graphql/handler/testserver/testserver.go +++ b/graphql/handler/testserver/testserver.go @@ -2,6 +2,7 @@ package testserver import ( "context" + "errors" "fmt" "time" @@ -122,7 +123,7 @@ func NewError() *TestServer { } ran = true - graphql.AddError(ctx, fmt.Errorf("resolver error")) + graphql.AddError(ctx, errors.New("resolver error")) return &graphql.Response{ Data: []byte(`null`), diff --git a/integration/server/resolver.go b/integration/server/resolver.go index 5a0d339831..6382f56092 100644 --- a/integration/server/resolver.go +++ b/integration/server/resolver.go @@ -4,6 +4,7 @@ package server import ( "context" + "errors" "fmt" "time" @@ -40,7 +41,7 @@ func (r *elementResolver) Error(ctx context.Context, obj *models.Element) (bool, // A silly hack to make the result order stable time.Sleep(time.Duration(obj.ID) * 10 * time.Millisecond) - return false, fmt.Errorf("boom") + return false, errors.New("boom") } func (r *elementResolver) Mismatched(ctx context.Context, obj *models.Element) ([]bool, error) { @@ -58,7 +59,7 @@ func (r *queryResolver) Error(ctx context.Context, typeArg *models.ErrorType) (b return false, &CustomError{"User message", "Internal Message"} } - return false, fmt.Errorf("normal error") + return false, errors.New("normal error") } func (r *queryResolver) Path(ctx context.Context) ([]*models.Element, error) { @@ -71,11 +72,11 @@ func (r *queryResolver) Coercion(ctx context.Context, input []*models.ListCoerci func (r *queryResolver) Date(ctx context.Context, filter models.DateFilter) (bool, error) { if filter.Value != "asdf" { - return false, fmt.Errorf("value must be asdf") + return false, errors.New("value must be asdf") } if *filter.Timezone != "UTC" { - return false, fmt.Errorf("timezone must be utc") + return false, errors.New("timezone must be utc") } if *filter.Op != models.DateFilterOpEq { diff --git a/internal/code/compare.go b/internal/code/compare.go index e521d31ee3..a3f15f186c 100644 --- a/internal/code/compare.go +++ b/internal/code/compare.go @@ -1,6 +1,7 @@ package code import ( + "errors" "fmt" "go/types" ) @@ -32,7 +33,7 @@ func CompatibleTypes(expected, actual types.Type) error { case *types.Array: if actual, ok := actual.(*types.Array); ok { if expected.Len() != actual.Len() { - return fmt.Errorf("array length differs") + return errors.New("array length differs") } return CompatibleTypes(expected.Elem(), actual.Elem()) @@ -50,7 +51,7 @@ func CompatibleTypes(expected, actual types.Type) error { case *types.Struct: if actual, ok := actual.(*types.Struct); ok { if expected.NumFields() != actual.NumFields() { - return fmt.Errorf("number of struct fields differ") + return errors.New("number of struct fields differ") } for i := 0; i < expected.NumFields(); i++ { diff --git a/main.go b/main.go index c920ec2737..a44996e8d2 100644 --- a/main.go +++ b/main.go @@ -100,17 +100,17 @@ var initCmd = &cli.Command{ cwd, err := os.Getwd() if err != nil { log.Println(err) - return fmt.Errorf("unable to determine current directory:%w", err) + return fmt.Errorf("unable to determine current directory: %w", err) } pkgName := code.ImportPathForDir(cwd) if pkgName == "" { - return fmt.Errorf( + return errors.New( "unable to determine import path for current directory, you probably need to run 'go mod init' first", ) } modRoot := findModuleRoot(cwd) if modRoot == "" { - return fmt.Errorf("go.mod is missing. Please, do 'go mod init' first\n") + return errors.New("go.mod is missing. Please, do 'go mod init' first\n") } // check schema and config don't already exist @@ -121,7 +121,7 @@ var initCmd = &cli.Command{ } _, err = config.LoadConfigFromDefaultLocations() if err == nil { - return fmt.Errorf("gqlgen.yml already exists in a parent directory\n") + return errors.New("gqlgen.yml already exists in a parent directory\n") } // create config diff --git a/plugin/resolvergen/resolver.go b/plugin/resolvergen/resolver.go index 97a2047716..a15f029ec4 100644 --- a/plugin/resolvergen/resolver.go +++ b/plugin/resolvergen/resolver.go @@ -138,7 +138,7 @@ func (m *Plugin) generatePerSchema(data *codegen.Data) error { continue } if implExists { - return fmt.Errorf("multiple plugins implement ResolverImplementer") + return errors.New("multiple plugins implement ResolverImplementer") } implExists = true resolver.ImplementationRender = rImpl.Implement