Skip to content

Commit

Permalink
Use std library for errors
Browse files Browse the repository at this point in the history
  • Loading branch information
rowanseymour committed May 20, 2024
1 parent 8627d1c commit 4db38cd
Show file tree
Hide file tree
Showing 15 changed files with 34 additions and 40 deletions.
6 changes: 3 additions & 3 deletions analytics/base.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package analytics

import "github.com/pkg/errors"
import "fmt"

// Backend is the interface for backends
type Backend interface {
Expand All @@ -21,7 +21,7 @@ func RegisterBackend(b Backend) {
func Start() error {
for _, b := range backends {
if err := b.Start(); err != nil {
return errors.Wrapf(err, "error starting %s analytics backend", b.Name())
return fmt.Errorf("error starting %s analytics backend: %w", b.Name(), err)
}
}
return nil
Expand All @@ -38,7 +38,7 @@ func Gauge(name string, value float64) {
func Stop() error {
for _, b := range backends {
if err := b.Stop(); err != nil {
return errors.Wrapf(err, "error stopping %s analytics backend", b.Name())
return fmt.Errorf("error stopping %s analytics backend: %w", b.Name(), err)
}
}
return nil
Expand Down
4 changes: 2 additions & 2 deletions dates/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ package dates

import (
"bytes"
"fmt"
"strings"
"time"

"github.com/nyaruka/gocommon/i18n"
"github.com/pkg/errors"
)

// Custom date/time formatting using layout strings like YYYY-MM-DD
Expand Down Expand Up @@ -236,7 +236,7 @@ func visitLayout(layout string, type_ LayoutType, mode LayoutMode, callback func
if exists && type_.Includes(layoutSeq.seqType) && (mode != ParsingMode || layoutSeq.parseable) {
mapped = layoutSeq.mapped
} else {
return errors.Errorf("'%s' is not valid in a %s %s layout", seq, type_, mode)
return fmt.Errorf("'%s' is not valid in a %s %s layout", seq, type_, mode)
}
}

Expand Down
5 changes: 2 additions & 3 deletions dates/parse.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package dates

import (
"fmt"
"time"

"github.com/pkg/errors"
)

// ZeroDateTime is our uninitialized datetime value
Expand Down Expand Up @@ -67,7 +66,7 @@ func parseError(err error) error {
}
}

return errors.Errorf("cannot parse '%s' as '%s'", typed.ValueElem, origLayoutSeq)
return fmt.Errorf("cannot parse '%s' as '%s'", typed.ValueElem, origLayoutSeq)
default:
return err
}
Expand Down
9 changes: 5 additions & 4 deletions dbutil/bulk.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ package dbutil

import (
"context"
"errors"
"fmt"
"strings"

"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)

// BulkQueryer is the DB/TX functionality needed for these bulk operations
Expand All @@ -32,13 +33,13 @@ func BulkSQL[T any](db BulkQueryer, sql string, structs []T) (string, []any, err
for i, value := range structs {
valueSQL, valueArgs, err := sqlx.Named(sql, value)
if err != nil {
return "", nil, errors.Wrapf(err, "error converting bulk insert args")
return "", nil, fmt.Errorf("error converting bulk insert args: %w", err)
}

args = append(args, valueArgs...)
argValues := extractValues(valueSQL)
if argValues == "" {
return "", nil, errors.Errorf("error extracting VALUES from sql: %s", valueSQL)
return "", nil, fmt.Errorf("error extracting VALUES from sql: %s", valueSQL)
}

// append to our global values, adding comma if necessary
Expand All @@ -50,7 +51,7 @@ func BulkSQL[T any](db BulkQueryer, sql string, structs []T) (string, []any, err

valuesSQL := extractValues(sql)
if valuesSQL == "" {
return "", nil, errors.Errorf("error extracting VALUES from sql: %s", sql)
return "", nil, fmt.Errorf("error extracting VALUES from sql: %s", sql)
}

return db.Rebind(strings.Replace(sql, valuesSQL, values.String(), -1)), args, nil
Expand Down
9 changes: 4 additions & 5 deletions dbutil/errors_test.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
package dbutil_test

import (
"errors"
"fmt"
"testing"

"github.com/lib/pq"
"github.com/nyaruka/gocommon/dbutil"

"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
)

func TestIsUniqueViolation(t *testing.T) {
var err error = &pq.Error{Code: pq.ErrorCode("23505")}

assert.True(t, dbutil.IsUniqueViolation(err))
assert.True(t, dbutil.IsUniqueViolation(errors.Wrap(err, "wrapped")))
assert.True(t, dbutil.IsUniqueViolation(fmt.Errorf("wrapped: %w", err)))
assert.False(t, dbutil.IsUniqueViolation(errors.New("boom")))
}

Expand All @@ -39,12 +38,12 @@ func TestQueryError(t *testing.T) {
assert.Equal(t, err, pqerr)

// can unwrap a wrapped error to find the first query error
wrapped := errors.Wrap(errors.Wrap(qerr, "error doing this"), "error doing that")
wrapped := fmt.Errorf("error doing that: %w", fmt.Errorf("error doing this: %w", qerr))
unwrapped := dbutil.AsQueryError(wrapped)
assert.Equal(t, qerr, unwrapped)

// nil if error was never a query error
wrapped = errors.Wrap(errors.New("error doing this"), "error doing that")
wrapped = fmt.Errorf("error doing that: %w", errors.New("error doing this"))
assert.Nil(t, dbutil.AsQueryError(wrapped))

query, params := unwrapped.Query()
Expand Down
8 changes: 4 additions & 4 deletions dbutil/scan.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package dbutil
import (
"database/sql"
"encoding/json"
"fmt"

"github.com/go-playground/validator/v10"
"github.com/pkg/errors"
)

var validate = validator.New()
Expand All @@ -15,12 +15,12 @@ func ScanJSON(rows *sql.Rows, destination any) error {
var raw json.RawMessage
err := rows.Scan(&raw)
if err != nil {
return errors.Wrap(err, "error scanning row JSON")
return fmt.Errorf("error scanning row JSON: %w", err)
}

err = json.Unmarshal(raw, destination)
if err != nil {
return errors.Wrap(err, "error unmarshalling row JSON")
return fmt.Errorf("error unmarshalling row JSON: %w", err)
}

return nil
Expand All @@ -34,7 +34,7 @@ func ScanAndValidateJSON(rows *sql.Rows, destination any) error {

err := validate.Struct(destination)
if err != nil {
return errors.Wrapf(err, "error validating unmarsalled JSON")
return fmt.Errorf("error validating unmarsalled JSON: %w", err)
}

return nil
Expand Down
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ require (
github.com/nyaruka/librato v1.1.1
github.com/nyaruka/null/v2 v2.0.3
github.com/nyaruka/phonenumbers v1.3.5
github.com/pkg/errors v0.9.1
github.com/shopspring/decimal v1.4.0
github.com/stretchr/testify v1.9.0
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842
Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,6 @@ github.com/nyaruka/null/v2 v2.0.3 h1:rdmMRQyVzrOF3Jff/gpU/7BDR9mQX0lcLl4yImsA3kw
github.com/nyaruka/null/v2 v2.0.3/go.mod h1:OCVeCkCXwrg5/qE6RU0c1oUVZBy+ZDrT+xYg1XSaIWA=
github.com/nyaruka/phonenumbers v1.3.5 h1:WZLbQn61j2E1OFnvpUTYbK/6hViUgl6tppJ55/E2iQM=
github.com/nyaruka/phonenumbers v1.3.5/go.mod h1:Ut+eFwikULbmCenH6InMKL9csUNLyxHuBLyfkpum11s=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
Expand Down
6 changes: 3 additions & 3 deletions httpx/access.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package httpx

import (
"fmt"
"net"
"net/http"
"strings"
"time"

"github.com/pkg/errors"
"golang.org/x/net/context"
)

Expand Down Expand Up @@ -63,13 +63,13 @@ func ParseNetworks(addrs ...string) ([]net.IP, []*net.IPNet, error) {
if strings.Contains(addr, "/") {
_, ipNet, err := net.ParseCIDR(addr)
if err != nil {
return nil, nil, errors.Errorf("couldn't parse '%s' as an IP network", addr)
return nil, nil, fmt.Errorf("couldn't parse '%s' as an IP network", addr)
}
ipNets = append(ipNets, ipNet)
} else {
ip := net.ParseIP(addr)
if ip == nil {
return nil, nil, errors.Errorf("couldn't parse '%s' as an IP address", addr)
return nil, nil, fmt.Errorf("couldn't parse '%s' as an IP address", addr)
}
ips = append(ips, ip)
}
Expand Down
2 changes: 1 addition & 1 deletion httpx/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package httpx
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"io"
"net/http"
Expand All @@ -13,7 +14,6 @@ import (

"github.com/gabriel-vasile/mimetype"
"github.com/nyaruka/gocommon/dates"
"github.com/pkg/errors"
)

// ErrResponseSize is returned when response size exceeds provided limit
Expand Down
2 changes: 1 addition & 1 deletion httpx/mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ package httpx
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"

"github.com/nyaruka/gocommon/jsonx"
"github.com/nyaruka/gocommon/stringsx"
"github.com/pkg/errors"
"golang.org/x/exp/maps"
)

Expand Down
5 changes: 2 additions & 3 deletions httpx/recorder.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (

"github.com/go-chi/chi/v5/middleware"
"github.com/nyaruka/gocommon/dates"
"github.com/pkg/errors"
)

// Recorder is a utility for creating traces of HTTP requests being handled
Expand All @@ -31,7 +30,7 @@ func NewRecorder(r *http.Request, w http.ResponseWriter, reconstruct bool) (*Rec

requestTrace, err := httputil.DumpRequest(or, true)
if err != nil {
return nil, errors.Wrap(err, "error dumping request")
return nil, fmt.Errorf("error dumping request: %w", err)
}

// if we cloned the request above, DumpRequest will have drained the body and saved a copy on the reconstructed
Expand Down Expand Up @@ -66,7 +65,7 @@ func (r *Recorder) End() error {
// and parse as response object
response, err := http.ReadResponse(bufio.NewReader(bytes.NewReader(responseTrace.Bytes())), r.Trace.Request)
if err != nil {
return errors.Wrap(err, "error reading response trace")
return fmt.Errorf("error reading response trace: %w", err)
}

r.Trace.Response = response
Expand Down
6 changes: 3 additions & 3 deletions i18n/language.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ package i18n

import (
"database/sql/driver"
"fmt"

"github.com/nyaruka/null/v2"
"github.com/pkg/errors"
"golang.org/x/text/language"
)

Expand Down Expand Up @@ -32,12 +32,12 @@ var NilLanguage = Language("")
// ParseLanguage returns a new Language for the passed in language string, or an error if not found
func ParseLanguage(lang string) (Language, error) {
if len(lang) != 3 {
return NilLanguage, errors.Errorf("iso-639-3 codes must be 3 characters, got: %s", lang)
return NilLanguage, fmt.Errorf("iso-639-3 codes must be 3 characters, got: %s", lang)
}

base, err := language.ParseBase(lang)
if err != nil {
return NilLanguage, errors.Errorf("unrecognized language code: %s", lang)
return NilLanguage, fmt.Errorf("unrecognized language code: %s", lang)
}

return Language(base.ISO3()), nil
Expand Down
7 changes: 3 additions & 4 deletions storage/s3.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/pkg/errors"
)

var s3BucketURL = "https://%s.s3.%s.amazonaws.com/%s"
Expand Down Expand Up @@ -88,12 +87,12 @@ func (s *s3Storage) Get(ctx context.Context, path string) (string, []byte, error
Key: aws.String(path),
})
if err != nil {
return "", nil, errors.Wrapf(err, "error getting S3 object")
return "", nil, fmt.Errorf("error getting S3 object: %w", err)
}

body, err := io.ReadAll(out.Body)
if err != nil {
return "", nil, errors.Wrapf(err, "error reading S3 object")
return "", nil, fmt.Errorf("error reading S3 object: %w", err)
}

return aws.StringValue(out.ContentType), body, nil
Expand All @@ -109,7 +108,7 @@ func (s *s3Storage) Put(ctx context.Context, path string, contentType string, bo
ACL: aws.String(s.acl),
})
if err != nil {
return "", errors.Wrapf(err, "error putting S3 object")
return "", fmt.Errorf("error putting S3 object: %w", err)
}

return s.url(path), nil
Expand Down
2 changes: 1 addition & 1 deletion urns/phone.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package urns

import (
"errors"
"regexp"
"strconv"
"strings"

"github.com/nyaruka/gocommon/i18n"
"github.com/nyaruka/phonenumbers"
"github.com/pkg/errors"
)

var nonTelCharsRegex = regexp.MustCompile(`[^0-9A-Za-z]`)
Expand Down

0 comments on commit 4db38cd

Please sign in to comment.