Use errors package all over the project

In general:
errors.New("thing") -> errors.New
fmt.Errorf("thing %s", arg) -> errors.Errorf
fmt.Errorf("thing %v", err) -> errors.Wrap
fmt.Errorf("thing %s %v", arg, err) -> errors.Wrapf
This commit is contained in:
Aaron L 2016-08-13 11:36:03 -07:00
parent 39eebe7a91
commit 5360d3094e
15 changed files with 55 additions and 53 deletions

View file

@ -7,6 +7,7 @@ import (
// Side-effect import sql driver
_ "github.com/lib/pq"
"github.com/pkg/errors"
"github.com/vattle/sqlboiler/bdb"
)
@ -139,7 +140,7 @@ func (p *PostgresDriver) Columns(tableName string) ([]bdb.Column, error) {
var unique bool
var defaultPtr *string
if err := rows.Scan(&colName, &colType, &defaultPtr, &nullable, &unique); err != nil {
return nil, fmt.Errorf("unable to scan for table %s: %s", tableName, err)
return nil, errors.Wrapf(err, "unable to scan for table %s", tableName)
}
if defaultPtr == nil {

View file

@ -11,6 +11,7 @@ import (
null "gopkg.in/nullbio/null.v4"
"github.com/pkg/errors"
"github.com/satori/go.uuid"
"github.com/vattle/sqlboiler/strmangle"
)
@ -60,9 +61,9 @@ func IsZeroValue(obj interface{}, shouldZero bool, columns ...string) []error {
zv := reflect.Zero(field.Type())
if shouldZero && !reflect.DeepEqual(field.Interface(), zv.Interface()) {
errs = append(errs, fmt.Errorf("Column with name %s is not zero value: %#v, %#v", c, field.Interface(), zv.Interface()))
errs = append(errs, errors.Errorf("Column with name %s is not zero value: %#v, %#v", c, field.Interface(), zv.Interface()))
} else if !shouldZero && reflect.DeepEqual(field.Interface(), zv.Interface()) {
errs = append(errs, fmt.Errorf("Column with name %s is zero value: %#v, %#v", c, field.Interface(), zv.Interface()))
errs = append(errs, errors.Errorf("Column with name %s is zero value: %#v, %#v", c, field.Interface(), zv.Interface()))
}
}
@ -93,20 +94,20 @@ func IsValueMatch(obj interface{}, columns []string, values []interface{}) []err
timeField = field.FieldByName("Time")
validField := field.FieldByName("Valid")
if validField.Interface() != values[i].(null.Time).Valid {
errs = append(errs, fmt.Errorf("Null.Time column with name %s Valid field does not match: %v ≠ %v", c, values[i].(null.Time).Valid, validField.Interface()))
errs = append(errs, errors.Errorf("Null.Time column with name %s Valid field does not match: %v ≠ %v", c, values[i].(null.Time).Valid, validField.Interface()))
}
}
if (rgxValidTime.MatchString(valTimeStr) && timeField.Interface() == reflect.Zero(timeField.Type()).Interface()) ||
(!rgxValidTime.MatchString(valTimeStr) && timeField.Interface() != reflect.Zero(timeField.Type()).Interface()) {
errs = append(errs, fmt.Errorf("Time column with name %s Time field does not match: %v ≠ %v", c, values[i], timeField.Interface()))
errs = append(errs, errors.Errorf("Time column with name %s Time field does not match: %v ≠ %v", c, values[i], timeField.Interface()))
}
continue
}
if !reflect.DeepEqual(field.Interface(), values[i]) {
errs = append(errs, fmt.Errorf("Column with name %s does not match value: %#v ≠ %#v", c, values[i], field.Interface()))
errs = append(errs, errors.Errorf("Column with name %s does not match value: %#v ≠ %#v", c, values[i], field.Interface()))
}
}
@ -131,7 +132,7 @@ func RandomizeSlice(obj interface{}, colTypes map[string]string, includeInvalid
}
if kind != exp {
return fmt.Errorf("[%d] RandomizeSlice object type should be *[]*Type but was: %s", i, ptrSlice.Type().String())
return errors.Errorf("[%d] RandomizeSlice object type should be *[]*Type but was: %s", i, ptrSlice.Type().String())
}
if kind == reflect.Struct {
@ -167,14 +168,14 @@ func RandomizeStruct(str interface{}, colTypes map[string]string, includeInvalid
value := reflect.ValueOf(str)
kind := value.Kind()
if kind != reflect.Ptr {
return fmt.Errorf("Outer element should be a pointer, given a non-pointer: %T", str)
return errors.Errorf("Outer element should be a pointer, given a non-pointer: %T", str)
}
// Check if it's a struct
value = value.Elem()
kind = value.Kind()
if kind != reflect.Struct {
return fmt.Errorf("Inner element should be a struct, given a non-struct: %T", str)
return errors.Errorf("Inner element should be a struct, given a non-struct: %T", str)
}
typ := value.Type()
@ -212,14 +213,14 @@ func RandomizeValidatedStruct(obj interface{}, validatedCols []string, colTypes
value := reflect.ValueOf(obj)
kind := value.Kind()
if kind != reflect.Ptr {
return fmt.Errorf("Outer element should be a pointer, given a non-pointer: %T", obj)
return errors.Errorf("Outer element should be a pointer, given a non-pointer: %T", obj)
}
// Check if it's a struct
value = value.Elem()
kind = value.Kind()
if kind != reflect.Struct {
return fmt.Errorf("Inner element should be a struct, given a non-struct: %T", obj)
return errors.Errorf("Inner element should be a struct, given a non-struct: %T", obj)
}
typ := value.Type()
@ -420,11 +421,11 @@ func randomizeField(field reflect.Value, fieldType string, includeInvalid bool)
case reflect.Slice:
sliceVal := typ.Elem()
if sliceVal.Kind() != reflect.Uint8 {
return fmt.Errorf("unsupported slice type: %T", typ.String())
return errors.Errorf("unsupported slice type: %T", typ.String())
}
newVal = randByteSlice(5+rand.Intn(20), sd.nextInt())
default:
return fmt.Errorf("unsupported type: %T", typ.String())
return errors.Errorf("unsupported type: %T", typ.String())
}
}

View file

@ -143,11 +143,11 @@ func removeDuplicates(dedup []string) []string {
var defaultTemplateImports = imports{
standard: importList{
`"errors"`,
`"fmt"`,
`"strings"`,
},
thirdParty: importList{
`"github.com/pkg/errors"`,
`"github.com/vattle/sqlboiler/boil"`,
`"github.com/vattle/sqlboiler/boil/qm"`,
`"github.com/vattle/sqlboiler/strmangle"`,
@ -169,10 +169,10 @@ var defaultTestTemplateImports = imports{
`"testing"`,
`"reflect"`,
`"time"`,
`"errors"`,
`"fmt"`,
},
thirdParty: importList{
`"github.com/pkg/errors"`,
`"gopkg.in/nullbio/null.v4"`,
`"github.com/vattle/sqlboiler/boil"`,
`"github.com/vattle/sqlboiler/boil/qm"`,
@ -222,11 +222,12 @@ var defaultTestMainImports = map[string]imports{
`"math/rand"`,
},
thirdParty: importList{
`"github.com/kat-co/vala"`,
`"github.com/pkg/errors"`,
`"github.com/spf13/viper"`,
`"github.com/vattle/sqlboiler/boil"`,
`"github.com/vattle/sqlboiler/bdb/drivers"`,
`_ "github.com/lib/pq"`,
`"github.com/spf13/viper"`,
`"github.com/kat-co/vala"`,
},
},
}

View file

@ -1,11 +1,11 @@
package main
import (
"fmt"
"reflect"
"sort"
"testing"
"github.com/pkg/errors"
"github.com/vattle/sqlboiler/bdb"
)
@ -146,7 +146,7 @@ func TestRemoveDuplicates(t *testing.T) {
for i := 0; i < len(possible)-1; i++ {
for j := i + 1; j < len(possible); j++ {
if possible[i] == possible[j] {
return fmt.Errorf("found duplicate: %s [%d] [%d]", possible[i], i, j)
return errors.Errorf("found duplicate: %s [%d] [%d]", possible[i], i, j)
}
}
}

View file

@ -101,7 +101,7 @@ func executeTemplates(e executeTemplateData) error {
resp, err := executeTemplate(e.templates.Template, tplName, e.data)
if err != nil {
return fmt.Errorf("Error generating template %s: %s", tplName, err)
return errors.Wrapf(err, "Error generating template %s", tplName)
}
out = append(out, resp)
}
@ -125,7 +125,7 @@ func executeSingletonTemplates(e executeTemplateData) error {
for _, tplName := range e.templates.Templates() {
resp, err := executeTemplate(e.templates.Template, tplName, e.data)
if err != nil {
return fmt.Errorf("Error generating template %s: %s", tplName, err)
return errors.Wrapf(err, "Error generating template %s", tplName)
}
fName := tplName
@ -184,25 +184,25 @@ func outHandler(outFolder string, fileName string, pkgName string, imps imports,
outFile, err := testHarnessFileOpen(path)
if err != nil {
return fmt.Errorf("Unable to create output file %s: %s", path, err)
return errors.Wrapf(err, "Unable to create output file %s", path)
}
defer outFile.Close()
out = outFile
if _, err := fmt.Fprintf(out, "package %s\n\n", pkgName); err != nil {
return fmt.Errorf("Unable to write package name %s to file: %s", pkgName, path)
return errors.Errorf("Unable to write package name %s to file: %s", pkgName, path)
}
impStr := buildImportString(imps)
if len(impStr) > 0 {
if _, err := fmt.Fprintf(out, "%s\n", impStr); err != nil {
return fmt.Errorf("Unable to write imports to file handle: %v", err)
return errors.Wrap(err, "Unable to write imports to file handle")
}
}
for _, templateOutput := range contents {
if _, err := fmt.Fprintf(out, "%s\n", templateOutput); err != nil {
return fmt.Errorf("Unable to write template output to file handle: %v", err)
return errors.Wrap(err, "Unable to write template output to file handle")
}
}

View file

@ -3,14 +3,13 @@
package main
import (
"fmt"
"os"
"strings"
"text/template"
"github.com/pkg/errors"
"github.com/vattle/sqlboiler/bdb"
"github.com/vattle/sqlboiler/bdb/drivers"
"github.com/pkg/errors"
)
const (
@ -225,7 +224,7 @@ func checkPKeys(tables []bdb.Table) error {
}
if len(missingPkey) != 0 {
return fmt.Errorf("primary key missing in tables (%s)", strings.Join(missingPkey, ", "))
return errors.Errorf("primary key missing in tables (%s)", strings.Join(missingPkey, ", "))
}
return nil

View file

@ -18,7 +18,7 @@ func (q {{$varNameSingular}}Query) One() (*{{$tableNameSingular}}, error) {
err := q.Bind(o)
if err != nil {
return nil, fmt.Errorf("{{.PkgName}}: failed to execute a one query for {{.Table.Name}}: %s", err)
return nil, errors.Wrap(err, "{{.PkgName}}: failed to execute a one query for {{.Table.Name}}")
}
return o, nil
@ -40,7 +40,7 @@ func (q {{$varNameSingular}}Query) All() ({{$tableNameSingular}}Slice, error) {
err := q.Bind(&o)
if err != nil {
return nil, fmt.Errorf("{{.PkgName}}: failed to assign all query results to {{$tableNameSingular}} slice: %s", err)
return nil, errors.Wrap(err, "{{.PkgName}}: failed to assign all query results to {{$tableNameSingular}} slice")
}
return o, nil
@ -64,7 +64,7 @@ func (q {{$varNameSingular}}Query) Count() (int64, error) {
err := boil.ExecQueryOne(q.Query).Scan(&count)
if err != nil {
return 0, fmt.Errorf("{{.PkgName}}: failed to count {{.Table.Name}} rows: %s", err)
return 0, errors.Wrap(err, "{{.PkgName}}: failed to count {{.Table.Name}} rows")
}
return count, nil
@ -89,7 +89,7 @@ func (q {{$varNameSingular}}Query) Exists() (bool, error) {
err := boil.ExecQueryOne(q.Query).Scan(&count)
if err != nil {
return false, fmt.Errorf("{{.PkgName}}: failed to check if {{.Table.Name}} exists: %s", err)
return false, errors.Wrap(err, "{{.PkgName}}: failed to check if {{.Table.Name}} exists")
}
return count > 0, nil

View file

@ -37,7 +37,7 @@ func {{$tableNameSingular}}Find(exec boil.Executor, {{$pkArgs}}, selectCols ...s
err := q.Bind({{$varNameSingular}})
if err != nil {
return nil, fmt.Errorf("{{.PkgName}}: unable to select from {{.Table.Name}}: %v", err)
return nil, errors.Wrap(err, "{{.PkgName}}: unable to select from {{.Table.Name}}")
}
return {{$varNameSingular}}, nil

View file

@ -44,7 +44,7 @@ func (o *{{$tableNameSingular}}) Insert(exec boil.Executor, whitelist ... string
if len(returnColumns) != 0 {
result, err := exec.Exec(ins, boil.GetStructValues(o, wl...)...)
if err != nil {
return fmt.Errorf("{{.PkgName}}: unable to insert into {{.Table.Name}}: %s", err)
return errors.Wrap(err, "{{.PkgName}}: unable to insert into {{.Table.Name}}")
}
lastId, err := result.lastInsertId()
@ -52,7 +52,7 @@ func (o *{{$tableNameSingular}}) Insert(exec boil.Executor, whitelist ... string
sel := fmt.Sprintf(`SELECT %s FROM {{.Table.Name}} WHERE %s`, strings.Join(returnColumns, `","`), strmangle.WhereClause(1, wl))
rows, err := exec.Query(sel, boil.GetStructValues(o, wl...)...)
if err != nil {
return fmt.Errorf("{{.PkgName}}: unable to insert into {{.Table.Name}}: %s", err)
return errors.Wrap(err, "{{.PkgName}}: unable to insert into {{.Table.Name}}")
}
defer rows.Close()
@ -60,7 +60,7 @@ func (o *{{$tableNameSingular}}) Insert(exec boil.Executor, whitelist ... string
ptrs := boil.GetStructPointers(o, returnColumns...)
for rows.Next() {
if err := rows.Scan(ptrs[i]); err != nil {
return fmt.Errorf("{{.PkgName}}: unable to get result of insert, scan failed for column %s index %d: %s\n\n%#v", returnColumns[i], i, err, ptrs)
return errors.Wrapf(err, "{{.PkgName}}: unable to get result of insert, scan failed for column %s index %d\n\n%#v", returnColumns[i], i, ptrs)
}
i++
}
@ -85,7 +85,7 @@ func (o *{{$tableNameSingular}}) Insert(exec boil.Executor, whitelist ... string
}
if err != nil {
return fmt.Errorf("{{.PkgName}}: unable to insert into {{.Table.Name}}: %s", err)
return errors.Wrap(err, "{{.PkgName}}: unable to insert into {{.Table.Name}}")
}
if err := o.doAfterCreateHooks(); err != nil {

View file

@ -55,11 +55,11 @@ func (o *{{$tableNameSingular}}) Update(exec boil.Executor, whitelist ... string
_, err = exec.Exec(query, values...)
} else {
return fmt.Errorf("{{.PkgName}}: unable to update {{.Table.Name}}, could not build whitelist")
return errors.New("{{.PkgName}}: unable to update {{.Table.Name}}, could not build whitelist")
}
if err != nil {
return fmt.Errorf("{{.PkgName}}: unable to update {{.Table.Name}} row: %s", err)
return errors.Wrap(err, "{{.PkgName}}: unable to update {{.Table.Name}} row")
}
if err := o.doAfterUpdateHooks(); err != nil {
@ -82,7 +82,7 @@ func (q {{$varNameSingular}}Query) UpdateAll(cols M) error {
_, err := boil.ExecQuery(q.Query)
if err != nil {
return fmt.Errorf("{{.PkgName}}: unable to update all for {{.Table.Name}}: %s", err)
return errors.Wrap(err, "{{.PkgName}}: unable to update all for {{.Table.Name}}")
}
return nil
@ -145,7 +145,7 @@ func (o {{$tableNameSingular}}Slice) UpdateAll(exec boil.Executor, cols M) error
_, err := exec.Exec(sql, args...)
if err != nil {
return fmt.Errorf("{{.PkgName}}: unable to update all in {{$varNameSingular}} slice: %s", err)
return errors.Wrap(err, "{{.PkgName}}: unable to update all in {{$varNameSingular}} slice")
}
return nil

View file

@ -46,7 +46,7 @@ func (o *{{$tableNameSingular}}) Upsert(exec boil.Executor, update bool, conflic
}
if err != nil {
return fmt.Errorf("{{.PkgName}}: unable to upsert for {{.Table.Name}}: %s", err)
return errors.Wrap(err, "{{.PkgName}}: unable to upsert for {{.Table.Name}}")
}
if err := o.doAfterUpsertHooks(); err != nil {

View file

@ -47,7 +47,7 @@ func (o *{{$tableNameSingular}}) Delete(exec boil.Executor) error {
_, err := boil.ExecQuery(query)
if err != nil {
return fmt.Errorf("{{.PkgName}}: unable to delete from {{.Table.Name}}: %s", err)
return errors.Wrap(err, "{{.PkgName}}: unable to delete from {{.Table.Name}}")
}
return nil
@ -70,7 +70,7 @@ func (q {{$varNameSingular}}Query) DeleteAll() error {
_, err := boil.ExecQuery(q.Query)
if err != nil {
return fmt.Errorf("{{.PkgName}}: unable to delete all from {{.Table.Name}}: %s", err)
return errors.Wrap(err, "{{.PkgName}}: unable to delete all from {{.Table.Name}}")
}
return nil
@ -123,7 +123,7 @@ func (o {{$tableNameSingular}}Slice) DeleteAll(exec boil.Executor) error {
_, err := exec.Exec(sql, args...)
if err != nil {
return fmt.Errorf("{{.PkgName}}: unable to delete all from {{$varNameSingular}} slice: %s", err)
return errors.Wrap(err, "{{.PkgName}}: unable to delete all from {{$varNameSingular}} slice")
}
return nil

View file

@ -81,7 +81,7 @@ func (o *{{$tableNameSingular}}Slice) ReloadAll(exec boil.Executor) error {
err := q.Bind(&{{$varNamePlural}})
if err != nil {
return fmt.Errorf("{{.PkgName}}: unable to reload all in {{$tableNameSingular}}Slice: %v", err)
return errors.Wrap(err, "{{.PkgName}}: unable to reload all in {{$tableNameSingular}}Slice")
}
*o = {{$varNamePlural}}

View file

@ -20,7 +20,7 @@ func {{$tableNameSingular}}Exists(exec boil.Executor, {{$pkArgs}}) (bool, error)
err := row.Scan(&exists)
if err != nil {
return false, fmt.Errorf("{{.PkgName}}: unable to check if {{.Table.Name}} exists: %v", err)
return false, errors.Wrap(err, "{{.PkgName}}: unable to check if {{.Table.Name}} exists")
}
return exists, nil

View file

@ -112,7 +112,7 @@ func setup() error {
// Initialize Viper and load the config file
err = InitViper()
if err != nil {
return fmt.Errorf("Unable to load config file: %s", err)
return errors.Wrap(err, "Unable to load config file")
}
viper.SetDefault("postgres.sslmode", "require")
@ -141,7 +141,7 @@ func setup() error {
).Check()
if err != nil {
return fmt.Errorf("Unable to load testCfg: %s", err.Error())
return errors.Wrap(err, "Unable to load testCfg")
}
err = dropTestDB()
@ -152,13 +152,13 @@ func setup() error {
fhSchema, err := ioutil.TempFile(os.TempDir(), "sqlboilerschema")
if err != nil {
return fmt.Errorf("Unable to create sqlboiler schema tmp file: %s", err)
return errors.Wrap(err, "Unable to create sqlboiler schema tmp file")
}
defer os.Remove(fhSchema.Name())
passDir, err := ioutil.TempDir(os.TempDir(), "sqlboiler")
if err != nil {
return fmt.Errorf("Unable to create sqlboiler tmp dir for postgres pw file: %s", err)
return errors.Wrap(err, "Unable to create sqlboiler tmp dir for postgres pw file")
}
defer os.RemoveAll(passDir)
@ -178,7 +178,7 @@ func setup() error {
err = ioutil.WriteFile(passFilePath, pwBytes, 0600)
if err != nil {
return fmt.Errorf("Unable to create pwfile in passDir: %s", err)
return errors.Wrap(err, "Unable to create pwfile in passDir")
}
// The params for the pg_dump command to dump the database schema
@ -247,7 +247,7 @@ func setup() error {
err = ioutil.WriteFile(testPassFilePath, testPwBytes, 0600)
if err != nil {
return fmt.Errorf("Unable to create testpwfile in passDir: %s", err)
return errors.Wrapf(err, "Unable to create testpwfile in passDir")
}
// The params for the psql schema import command