all: Tweak error creation (#6391)

- In the few places where we wrap errors, use the new Go 1.13 "%w"
  construction instead of %s or %v.

- Where we create errors with constant strings, consistently use
  errors.New and not fmt.Errorf.

- Remove capitalization from errors in the few places where we had that.
This commit is contained in:
Jakob Borg 2020-03-03 22:40:00 +01:00 committed by GitHub
parent eddc8d3ff2
commit dd92b2b8f4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 67 additions and 60 deletions

View File

@ -10,6 +10,7 @@ import (
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"net/http"
@ -80,16 +81,16 @@ func (c *APIClient) Post(url, body string) (*http.Response, error) {
func checkResponse(response *http.Response) error {
if response.StatusCode == 404 {
return fmt.Errorf("Invalid endpoint or API call")
return errors.New("invalid endpoint or API call")
} else if response.StatusCode == 403 {
return fmt.Errorf("Invalid API key")
return errors.New("invalid API key")
} else if response.StatusCode != 200 {
data, err := responseToBArray(response)
if err != nil {
return err
}
body := strings.TrimSpace(string(data))
return fmt.Errorf("Unexpected HTTP status returned: %s\n%s", response.Status, body)
return fmt.Errorf("unexpected HTTP status returned: %s\n%s", response.Status, body)
}
return nil
}

View File

@ -7,6 +7,7 @@
package main
import (
"errors"
"fmt"
"strings"
@ -54,7 +55,7 @@ func errorsPush(c *cli.Context) error {
if body != "" {
errStr += "\nBody: " + body
}
return fmt.Errorf(errStr)
return errors.New(errStr)
}
return nil
}

View File

@ -60,7 +60,7 @@ func compareDirectories(dirs ...string) error {
} else if res[i].name > res[0].name {
return fmt.Errorf("%s missing %v (present in %s)", dirs[i], res[0], dirs[0])
}
return fmt.Errorf("Mismatch; %v (%s) != %v (%s)", res[i], dirs[i], res[0], dirs[0])
return fmt.Errorf("mismatch; %v (%s) != %v (%s)", res[i], dirs[i], res[0], dirs[0])
}
}

View File

@ -10,6 +10,7 @@ import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
@ -494,7 +495,7 @@ func handleRelayTest(request request) {
if debug {
log.Println("Test for relay", request.relay, "failed")
}
request.result <- result{fmt.Errorf("connection test failed"), 0}
request.result <- result{errors.New("connection test failed"), 0}
return
}

View File

@ -14,6 +14,7 @@ import (
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"flag"
"fmt"
"math/big"
@ -191,7 +192,7 @@ func pemBlockForKey(priv interface{}) (*pem.Block, error) {
}
return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}, nil
default:
return nil, fmt.Errorf("unknown key type")
return nil, errors.New("unknown key type")
}
}

View File

@ -266,10 +266,10 @@ type report struct {
func (r *report) Validate() error {
if r.UniqueID == "" || r.Version == "" || r.Platform == "" {
return fmt.Errorf("missing required field")
return errors.New("missing required field")
}
if len(r.Date) != 8 {
return fmt.Errorf("date not initialized")
return errors.New("date not initialized")
}
// Some fields may not be null.

View File

@ -543,7 +543,7 @@ func startHTTP(cfg *mockedConfig) (string, *suture.Supervisor, error) {
tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
supervisor.Stop()
return "", nil, fmt.Errorf("Weird address from API service: %v", err)
return "", nil, fmt.Errorf("weird address from API service: %w", err)
}
host, _, _ := net.SplitHostPort(cfg.gui.RawAddress)

View File

@ -295,11 +295,11 @@ func (cfg *Configuration) clean() error {
}
if folder.Path == "" {
return fmt.Errorf("folder %q: %v", folder.ID, errFolderPathEmpty)
return fmt.Errorf("folder %q: %w", folder.ID, errFolderPathEmpty)
}
if _, ok := existingFolders[folder.ID]; ok {
return fmt.Errorf("folder %q: %v", folder.ID, errFolderIDDuplicate)
return fmt.Errorf("folder %q: %w", folder.ID, errFolderIDDuplicate)
}
existingFolders[folder.ID] = folder

View File

@ -941,7 +941,7 @@ func (s *service) validateIdentity(c internalConn, expectedID protocol.DeviceID)
if remoteID == s.myID {
l.Infof("Connected to myself (%s) at %s - should not happen", remoteID, c)
c.Close()
return fmt.Errorf("connected to self")
return errors.New("connected to self")
}
// We should see the expected device ID

View File

@ -8,6 +8,7 @@ package db
import (
"bytes"
"errors"
"fmt"
"strings"
@ -32,8 +33,8 @@ const (
)
var (
errFolderIdxMissing = fmt.Errorf("folder db index missing")
errDeviceIdxMissing = fmt.Errorf("device db index missing")
errFolderIdxMissing = errors.New("folder db index missing")
errDeviceIdxMissing = errors.New("device db index missing")
)
type databaseDowngradeError struct {

View File

@ -11,7 +11,6 @@ package fs
import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
@ -137,7 +136,7 @@ func (f *BasicFilesystem) Roots() ([]string, error) {
hr, _, _ := getLogicalDriveStringsHandle.Call(uintptr(unsafe.Pointer(&bufferSize)), uintptr(unsafe.Pointer(&buffer)))
if hr == 0 {
return nil, fmt.Errorf("Syscall failed")
return nil, errors.New("syscall failed")
}
var drives []string

View File

@ -508,13 +508,13 @@ func parseIgnoreFile(fs fs.Filesystem, fd io.Reader, currentFile string, cd Chan
case strings.HasPrefix(line, "#include"):
fields := strings.SplitN(line, " ", 2)
if len(fields) != 2 {
err = fmt.Errorf("failed to parse #include line: no file?")
err = errors.New("failed to parse #include line: no file?")
break
}
includeRel := strings.TrimSpace(fields[1])
if includeRel == "" {
err = fmt.Errorf("failed to parse #include line: no file?")
err = errors.New("failed to parse #include line: no file?")
break
}

View File

@ -345,7 +345,7 @@ func (m *model) startFolderLocked(cfg config.FolderConfiguration) {
var err error
ver, err = versioner.New(ffs, cfg.Versioning)
if err != nil {
panic(fmt.Errorf("creating versioner: %v", err))
panic(fmt.Errorf("creating versioner: %w", err))
}
if service, ok := ver.(suture.Service); ok {
// The versioner implements the suture.Service interface, so
@ -1688,7 +1688,7 @@ func (m *model) GetIgnores(folder string) ([]string, []string, error) {
if !cfgOk {
cfg, cfgOk = m.cfg.Folders()[folder]
if !cfgOk {
return nil, nil, fmt.Errorf("Folder %s does not exist", folder)
return nil, nil, fmt.Errorf("folder %s does not exist", folder)
}
}

View File

@ -5,7 +5,6 @@ package protocol
import (
"encoding/binary"
"errors"
"fmt"
"io"
)
@ -66,7 +65,7 @@ func readHello(c io.Reader) (HelloResult, error) {
}
msgSize := binary.BigEndian.Uint16(header[:2])
if msgSize > 32767 {
return HelloResult{}, fmt.Errorf("hello message too big")
return HelloResult{}, errors.New("hello message too big")
}
buf := make([]byte, msgSize)
if _, err := io.ReadFull(c, buf); err != nil {

View File

@ -27,7 +27,7 @@ func (a luhnAlphabet) generate(s string) (rune, error) {
for i := range s {
codepoint := strings.IndexByte(string(a), s[i])
if codepoint == -1 {
return 0, fmt.Errorf("Digit %q not valid in alphabet %q", s[i], a)
return 0, fmt.Errorf("digit %q not valid in alphabet %q", s[i], a)
}
addend := factor * codepoint
if factor == 2 {

View File

@ -232,7 +232,7 @@ func (p *Process) Events(since int) ([]Event, error) {
dec.UseNumber()
err = dec.Decode(&evs)
if err != nil {
return nil, fmt.Errorf("Events: %s in %q", err, bs)
return nil, fmt.Errorf("events: %w in %q", err, bs)
}
return evs, err
}
@ -398,7 +398,7 @@ func (p *Process) readResponse(resp *http.Response) ([]byte, error) {
return bs, err
}
if resp.StatusCode != 200 {
return bs, fmt.Errorf("%s", resp.Status)
return bs, errors.New(resp.Status)
}
return bs, nil
}

View File

@ -38,7 +38,7 @@ type RelayClient interface {
func NewClient(uri *url.URL, certs []tls.Certificate, invitations chan protocol.SessionInvitation, timeout time.Duration) (RelayClient, error) {
factory, ok := supportedSchemes[uri.Scheme]
if !ok {
return nil, fmt.Errorf("Unsupported scheme: %s", uri.Scheme)
return nil, fmt.Errorf("unsupported scheme: %s", uri.Scheme)
}
return factory(uri, certs, invitations, timeout), nil

View File

@ -6,6 +6,7 @@ import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
@ -100,7 +101,7 @@ func (c *dynamicClient) serve(ctx context.Context) error {
}
}
l.Debugln(c, "could not find a connectable relay")
return fmt.Errorf("could not find a connectable relay")
return errors.New("could not find a connectable relay")
}
func (c *dynamicClient) Stop() {

View File

@ -19,7 +19,7 @@ import (
func GetInvitationFromRelay(ctx context.Context, uri *url.URL, id syncthingprotocol.DeviceID, certs []tls.Certificate, timeout time.Duration) (protocol.SessionInvitation, error) {
if uri.Scheme != "relay" {
return protocol.SessionInvitation{}, fmt.Errorf("Unsupported relay scheme: %v", uri.Scheme)
return protocol.SessionInvitation{}, fmt.Errorf("unsupported relay scheme: %v", uri.Scheme)
}
ctx, cancel := context.WithTimeout(ctx, timeout)
@ -53,7 +53,7 @@ func GetInvitationFromRelay(ctx context.Context, uri *url.URL, id syncthingproto
switch msg := message.(type) {
case protocol.Response:
return protocol.SessionInvitation{}, fmt.Errorf("Incorrect response code %d: %s", msg.Code, msg.Message)
return protocol.SessionInvitation{}, fmt.Errorf("incorrect response code %d: %s", msg.Code, msg.Message)
case protocol.SessionInvitation:
l.Debugln("Received invitation", msg, "via", conn.LocalAddr())
ip := net.IP(msg.Address)
@ -96,7 +96,7 @@ func JoinSession(ctx context.Context, invitation protocol.SessionInvitation) (ne
switch msg := message.(type) {
case protocol.Response:
if msg.Code != 0 {
return nil, fmt.Errorf("Incorrect response code %d: %s", msg.Code, msg.Message)
return nil, fmt.Errorf("incorrect response code %d: %s", msg.Code, msg.Message)
}
return conn, nil
default:

View File

@ -73,9 +73,9 @@ func (c *staticClient) serve(ctx context.Context) error {
c.mut.Unlock()
messages := make(chan interface{})
errors := make(chan error, 1)
errorsc := make(chan error, 1)
go messageReader(ctx, c.conn, messages, errors)
go messageReader(ctx, c.conn, messages, errorsc)
timeout := time.NewTimer(c.messageTimeout)
@ -102,7 +102,7 @@ func (c *staticClient) serve(ctx context.Context) error {
case protocol.RelayFull:
l.Infof("Disconnected from relay %s due to it becoming full.", c.uri)
return fmt.Errorf("relay full")
return errors.New("relay full")
default:
l.Infoln("Relay: protocol error: unexpected message %v", msg)
@ -113,13 +113,13 @@ func (c *staticClient) serve(ctx context.Context) error {
l.Debugln(c, "stopping")
return nil
case err := <-errors:
case err := <-errorsc:
l.Infof("Disconnecting from relay %s due to error: %s", c.uri, err)
return err
case <-timeout.C:
l.Debugln(c, "timed out")
return fmt.Errorf("timed out")
return errors.New("timed out")
}
}
}
@ -205,7 +205,7 @@ func (c *staticClient) join() error {
}
case protocol.RelayFull:
return fmt.Errorf("relay full")
return errors.New("relay full")
default:
return fmt.Errorf("protocol error: expecting response got %v", msg)
@ -221,7 +221,7 @@ func performHandshakeAndValidation(conn *tls.Conn, uri *url.URL) error {
cs := conn.ConnectionState()
if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != protocol.ProtocolName {
return fmt.Errorf("protocol negotiation error")
return errors.New("protocol negotiation error")
}
q := uri.Query()

View File

@ -3,7 +3,7 @@
package protocol
import (
"fmt"
"errors"
"io"
)
@ -53,7 +53,7 @@ func WriteMessage(w io.Writer, message interface{}) error {
payload, err = msg.MarshalXDR()
header.messageType = messageTypeRelayFull
default:
err = fmt.Errorf("Unknown message type")
err = errors.New("unknown message type")
}
if err != nil {
@ -84,7 +84,7 @@ func ReadMessage(r io.Reader) (interface{}, error) {
}
if header.magic != magic {
return nil, fmt.Errorf("magic mismatch")
return nil, errors.New("magic mismatch")
}
buf = make([]byte, int(header.messageLength))
@ -127,5 +127,5 @@ func ReadMessage(r io.Reader) (interface{}, error) {
return msg, err
}
return nil, fmt.Errorf("Unknown message type")
return nil, errors.New("unknown message type")
}

View File

@ -536,7 +536,7 @@ func (w *walker) handleError(ctx context.Context, context, path string, err erro
l.Infof("Scanner (folder %s, item %q): %s: %v", w.Folder, path, context, err)
select {
case finishedChan <- ScanResult{
Err: fmt.Errorf("%s: %s", context, err.Error()),
Err: fmt.Errorf("%s: %w", context, err),
Path: path,
}:
case <-ctx.Done():

View File

@ -10,6 +10,7 @@ import (
"bytes"
"context"
"crypto/rand"
"errors"
"fmt"
"io"
"io/ioutil"
@ -836,7 +837,7 @@ func verify(r io.Reader, blocksize int, blocks []protocol.BlockInfo) error {
bs := make([]byte, 1)
n, err := r.Read(bs)
if n != 0 || err != io.EOF {
return fmt.Errorf("file continues past end of blocks")
return errors.New("file continues past end of blocks")
}
return nil

View File

@ -14,7 +14,6 @@ import (
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"net"
"os"
@ -26,7 +25,7 @@ import (
)
var (
ErrIdentificationFailed = fmt.Errorf("failed to identify socket type")
ErrIdentificationFailed = errors.New("failed to identify socket type")
)
var (
@ -239,7 +238,7 @@ func pemBlockForKey(priv interface{}) (*pem.Block, error) {
}
return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}, nil
default:
return nil, fmt.Errorf("unknown key type")
return nil, errors.New("unknown key type")
}
}

View File

@ -15,6 +15,7 @@ import (
"compress/gzip"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
@ -366,10 +367,10 @@ func archiveFileVisitor(dir string, tempFile *string, signature *[]byte, archive
func verifyUpgrade(archiveName, tempName string, sig []byte) error {
if tempName == "" {
return fmt.Errorf("no upgrade found")
return errors.New("no upgrade found")
}
if sig == nil {
return fmt.Errorf("no signature found")
return errors.New("no signature found")
}
l.Debugf("checking signature\n%s", sig)

View File

@ -7,7 +7,6 @@
package versioner
import (
"fmt"
"path/filepath"
"regexp"
"sort"
@ -20,9 +19,11 @@ import (
"github.com/syncthing/syncthing/lib/util"
)
var errDirectory = fmt.Errorf("cannot restore on top of a directory")
var errNotFound = fmt.Errorf("version not found")
var errFileAlreadyExists = fmt.Errorf("file already exists")
var (
errDirectory = errors.New("cannot restore on top of a directory")
errNotFound = errors.New("version not found")
errFileAlreadyExists = errors.New("file already exists")
)
// TagFilename inserts ~tag just before the extension of the filename.
func TagFilename(name, tag string) string {

View File

@ -9,6 +9,7 @@
package versioner
import (
"errors"
"fmt"
"time"
@ -32,7 +33,7 @@ type factory func(filesystem fs.Filesystem, params map[string]string) Versioner
var factories = make(map[string]factory)
var ErrRestorationNotSupported = fmt.Errorf("version restoration not supported with the current versioner")
var ErrRestorationNotSupported = errors.New("version restoration not supported with the current versioner")
const (
TimeFormat = "20060102-150405"

View File

@ -68,5 +68,5 @@ func checkCopyright(path string, info os.FileInfo, err error) error {
}
}
return fmt.Errorf("Missing copyright in %s?", path)
return fmt.Errorf("missing copyright in %s?", path)
}

View File

@ -265,7 +265,7 @@ func scSyncAndCompare(p []*rc.Process, expected [][]fileInfo) error {
return err
}
if err := compareDirectoryContents(actual, expected[0]); err != nil {
return fmt.Errorf("%s: %v", dir, err)
return fmt.Errorf("%s: %w", dir, err)
}
}
@ -276,7 +276,7 @@ func scSyncAndCompare(p []*rc.Process, expected [][]fileInfo) error {
return err
}
if err := compareDirectoryContents(actual, expected[1]); err != nil {
return fmt.Errorf("%s: %v", dir, err)
return fmt.Errorf("%s: %w", dir, err)
}
}
}
@ -288,7 +288,7 @@ func scSyncAndCompare(p []*rc.Process, expected [][]fileInfo) error {
return err
}
if err := compareDirectoryContents(actual, expected[2]); err != nil {
return fmt.Errorf("%s: %v", dir, err)
return fmt.Errorf("%s: %w", dir, err)
}
}
}

View File

@ -330,7 +330,7 @@ func compareDirectories(dirs ...string) error {
for i := 1; i < len(res); i++ {
if res[i] != res[0] {
close(abort)
return fmt.Errorf("Mismatch; %#v (%s) != %#v (%s)", res[i], dirs[i], res[0], dirs[0])
return fmt.Errorf("mismatch; %#v (%s) != %#v (%s)", res[i], dirs[i], res[0], dirs[0])
}
}
@ -381,7 +381,7 @@ func compareDirectoryContents(actual, expected []fileInfo) error {
for i := range actual {
if actual[i] != expected[i] {
return fmt.Errorf("Mismatch; actual %#v != expected %#v", actual[i], expected[i])
return fmt.Errorf("mismatch; actual %#v != expected %#v", actual[i], expected[i])
}
}
return nil