Skip to content

Commit

Permalink
refactor: use errors.New instead of fmt.Errorf (#3112)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandear committed May 29, 2024
1 parent 93f6366 commit 4114515
Show file tree
Hide file tree
Showing 37 changed files with 122 additions and 98 deletions.
7 changes: 7 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -45,6 +51,7 @@ linters:
- ineffassign
- misspell
- nakedret
- perfsprint
- prealloc
- revive
- staticcheck
Expand Down
3 changes: 2 additions & 1 deletion _examples/dataloader/resolvers.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"context"
"fmt"
"math/rand"
"strconv"
"time"
)

Expand Down Expand Up @@ -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
}
Expand Down
8 changes: 4 additions & 4 deletions _examples/scalars/model/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
5 changes: 2 additions & 3 deletions _examples/todo/todo.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ package todo
import (
"context"
"errors"
"fmt"
"time"

"github.com/mitchellh/mapstructure"
Expand Down Expand Up @@ -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")
}
}

Expand Down
3 changes: 2 additions & 1 deletion client/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package client

import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http/httptest"
Expand Down Expand Up @@ -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)
}
Expand Down
4 changes: 2 additions & 2 deletions codegen/config/binder.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}" {
Expand All @@ -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)
Expand Down
5 changes: 3 additions & 2 deletions codegen/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package config

import (
"bytes"
"errors"
"fmt"
"go/types"
"io"
Expand Down Expand Up @@ -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 {
Expand Down
9 changes: 5 additions & 4 deletions codegen/config/exec.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config

import (
"errors"
"fmt"
"go/types"
"path/filepath"
Expand Down Expand Up @@ -38,23 +39,23 @@ 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:
return fmt.Errorf("invalid layout %s", r.Layout)
}

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() != "" {
Expand Down
8 changes: 4 additions & 4 deletions codegen/config/package.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package config

import (
"fmt"
"errors"
"go/types"
"path/filepath"
"strings"
Expand Down Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion codegen/config/resolver.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config

import (
"errors"
"fmt"
"go/types"
"path/filepath"
Expand Down Expand Up @@ -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() != "" {
Expand Down
7 changes: 4 additions & 3 deletions codegen/data.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package codegen

import (
"errors"
"fmt"
"os"
"path/filepath"
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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{
Expand Down
2 changes: 1 addition & 1 deletion codegen/field.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion codegen/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
5 changes: 3 additions & 2 deletions codegen/templates/import.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package templates

import (
"errors"
"fmt"
"go/types"
"strconv"
Expand Down Expand Up @@ -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{
Expand Down
5 changes: 3 additions & 2 deletions codegen/templates/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package templates

import (
"bytes"
"errors"
"fmt"
"go/types"
"io/fs"
Expand Down Expand Up @@ -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)}

Expand Down Expand Up @@ -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:
Expand Down
17 changes: 9 additions & 8 deletions codegen/testserver/followschema/directive_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package followschema

import (
"context"
"errors"
"fmt"
"testing"

Expand Down Expand Up @@ -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 {
Expand All @@ -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)
}
Expand Down
Loading

0 comments on commit 4114515

Please sign in to comment.