From 516f6e369ac5f2641d476bb282a512c69fa69647 Mon Sep 17 00:00:00 2001 From: tengu-alt Date: Wed, 29 May 2024 12:48:03 +0300 Subject: [PATCH] error messages were refactored --- cluster.go | 6 +++--- conn.go | 14 ++++++------- control.go | 12 +++++------ dial.go | 4 ++-- filters.go | 2 +- frame.go | 54 +++++++++++++++++++++++++------------------------- helpers.go | 2 +- host_source.go | 30 ++++++++++++++++------------ marshal.go | 12 ++++++----- metadata.go | 10 +++++----- policies.go | 2 +- session.go | 34 +++++++++++++++---------------- token.go | 2 +- topology.go | 8 ++++---- udt_test.go | 2 +- uuid.go | 6 +++--- 16 files changed, 103 insertions(+), 97 deletions(-) diff --git a/cluster.go b/cluster.go index 13e62f3b0..ddf5cfbcb 100644 --- a/cluster.go +++ b/cluster.go @@ -329,7 +329,7 @@ func (cfg *ClusterConfig) filterHost(host *HostInfo) bool { } var ( - ErrNoHosts = errors.New("no hosts provided") - ErrNoConnectionsStarted = errors.New("no connections were made when creating the session") - ErrHostQueryFailed = errors.New("unable to populate Hosts") + ErrAuthenticatorAndAuthProvider = errors.New("gocql: Can't use both Authenticator and AuthProvider in cluster config.") + ErrNoHosts = errors.New("gocql: no hosts provided") + ErrNoConnectionsStarted = errors.New("gocql: no connections were made when creating the session") ) diff --git a/conn.go b/conn.go index 3daca6250..7cd13d93c 100644 --- a/conn.go +++ b/conn.go @@ -94,7 +94,7 @@ type PasswordAuthenticator struct { func (p PasswordAuthenticator) Challenge(req []byte) ([]byte, Authenticator, error) { if !approve(string(req), p.AllowedAuthenticators) { - return nil, nil, fmt.Errorf("unexpected authenticator %q", req) + return nil, nil, fmt.Errorf("gocql: unexpected authenticator %q", req) } resp := make([]byte, 2+len(p.Username)+len(p.Password)) resp[0] = 0 @@ -484,7 +484,7 @@ func (s *startupCoordinator) startup(ctx context.Context, supported map[string][ func (s *startupCoordinator) authenticateHandshake(ctx context.Context, authFrame *authenticateFrame) error { if s.conn.auth == nil { - return fmt.Errorf("authentication required (using %q)", authFrame.class) + return fmt.Errorf("gocql: authentication required (using %q)", authFrame.class) } resp, challenger, err := s.conn.auth.Challenge([]byte(authFrame.class)) @@ -517,7 +517,7 @@ func (s *startupCoordinator) authenticateHandshake(ctx context.Context, authFram data: resp, } default: - return fmt.Errorf("unknown frame response during authentication: %v", v) + return fmt.Errorf("gocql: unknown frame response during authentication: %v", v) } } } @@ -1019,7 +1019,7 @@ func (c *Conn) addCall(call *callReq) error { } existingCall := c.calls[call.streamID] if existingCall != nil { - return fmt.Errorf("attempting to use stream already in use: %d -> %d", call.streamID, + return fmt.Errorf("gocql: attempting to use stream already in use: %d -> %d", call.streamID, existingCall.streamID) } c.calls[call.streamID] = call @@ -1291,7 +1291,7 @@ func (c *Conn) prepareStatement(ctx context.Context, stmt string, tracer Tracer) response: x.respMeta, } case error: - flight.err = x + flight.err = fmt.Errorf("cassandra: %w", x) default: flight.err = NewErrProtocol("Unknown type in response to prepare frame: %s", x) } @@ -1528,7 +1528,7 @@ func (c *Conn) UseKeyspace(keyspace string) error { switch x := resp.(type) { case *resultKeyspaceFrame: case error: - return x + return fmt.Errorf("cassandra: %w", x) default: return NewErrProtocol("unknown frame in response to USE: %v", x) } @@ -1636,7 +1636,7 @@ func (c *Conn) executeBatch(ctx context.Context, batch *Batch) *Iter { return iter case error: - return &Iter{err: x, framer: framer} + return &Iter{err: fmt.Errorf("cassandra: %w", x), framer: framer} default: return &Iter{err: NewErrProtocol("Unknown type in response to batch statement: %s", x), framer: framer} } diff --git a/control.go b/control.go index b30b44ea3..bb5fef5ff 100644 --- a/control.go +++ b/control.go @@ -155,7 +155,7 @@ func hostInfo(addr string, defaultPort int) ([]*HostInfo, error) { if err != nil { return nil, err } else if len(ips) == 0 { - return nil, fmt.Errorf("no IP's returned from DNS lookup for %q", addr) + return nil, fmt.Errorf("gocql: no IP's returned from DNS lookup for %q", addr) } // Filter to v4 addresses if any present @@ -275,7 +275,7 @@ func (c *controlConn) connect(hosts []*HostInfo) error { conn = nil } if conn == nil { - return fmt.Errorf("unable to connect to initial hosts: %v", err) + return fmt.Errorf("gocql: unable to connect to initial hosts: %w", err) } // we could fetch the initial ring here and update initial host data. So that @@ -302,11 +302,11 @@ func (c *controlConn) setupConn(conn *Conn) error { host = c.session.ring.addOrUpdate(host) if c.session.cfg.filterHost(host) { - return fmt.Errorf("host was filtered: %v", host.ConnectAddress()) + return fmt.Errorf("gocql: host was filtered: %v", host.ConnectAddress()) } if err := c.registerEvents(conn); err != nil { - return fmt.Errorf("register events: %v", err) + return fmt.Errorf("gocql: register events: %w", err) } ch := &connHost{ @@ -356,7 +356,7 @@ func (c *controlConn) registerEvents(conn *Conn) error { if err != nil { return err } else if _, ok := frame.(*readyFrame); !ok { - return fmt.Errorf("unexpected frame in response to register: got %T: %v\n", frame, frame) + return fmt.Errorf("gocql: unexpected frame in response to register: got %T: %v\n", frame, frame) } return nil @@ -413,7 +413,7 @@ func (c *controlConn) attemptReconnect() (*Conn, error) { // changed their IPs while keeping the same hostname(s). initialHosts, resolvErr := addrsToHosts(c.session.cfg.Hosts, c.session.cfg.Port, c.session.logger) if resolvErr != nil { - return nil, fmt.Errorf("resolve contact points' hostnames: %v", resolvErr) + return nil, fmt.Errorf("gocql: resolve contact points' hostnames: %w", resolvErr) } return c.attemptReconnectToAnyOfHosts(initialHosts) diff --git a/dial.go b/dial.go index 8c7251d62..84b817cc8 100644 --- a/dial.go +++ b/dial.go @@ -64,9 +64,9 @@ func (hd *defaultHostDialer) DialHost(ctx context.Context, host *HostInfo) (*Dia port := host.Port() if !validIpAddr(ip) { - return nil, fmt.Errorf("host missing connect ip address: %v", ip) + return nil, fmt.Errorf("gocql: host missing connect ip address: %v", ip) } else if port == 0 { - return nil, fmt.Errorf("host missing port: %v", port) + return nil, fmt.Errorf("gocql: host missing port: %v", port) } connAddr := host.ConnectAddressAndPort() diff --git a/filters.go b/filters.go index f51de7fe2..1ca76a7d5 100644 --- a/filters.go +++ b/filters.go @@ -67,7 +67,7 @@ func WhiteListHostFilter(hosts ...string) HostFilter { hostInfos, err := addrsToHosts(hosts, 9042, nopLogger{}) if err != nil { // dont want to panic here, but rather not break the API - panic(fmt.Errorf("unable to lookup host info from address: %v", err)) + panic(fmt.Errorf("gocql: unable to lookup host info from address: %w", err)) } m := make(map[string]bool, len(hostInfos)) diff --git a/frame.go b/frame.go index d374ae574..4d188be35 100644 --- a/frame.go +++ b/frame.go @@ -254,7 +254,7 @@ func (c *Consistency) UnmarshalText(text []byte) error { case "LOCAL_ONE": *c = LocalOne default: - return fmt.Errorf("invalid consistency %q", string(text)) + return fmt.Errorf("gocql: invalid consistency %q", string(text)) } return nil @@ -315,7 +315,7 @@ func (s *SerialConsistency) UnmarshalText(text []byte) error { case "LOCAL_SERIAL": *s = LocalSerial default: - return fmt.Errorf("invalid consistency %q", string(text)) + return fmt.Errorf("gocql: invalid consistency %q", string(text)) } return nil @@ -326,7 +326,7 @@ const ( ) var ( - ErrFrameTooBig = errors.New("frame length is bigger than the maximum allowed") + ErrFrameTooBig = errors.New("gocql: frame length is bigger than the maximum allowed") ) const maxFrameHeaderSize = 9 @@ -469,7 +469,7 @@ func readHeader(r io.Reader, p []byte) (head frameHeader, err error) { if version > protoVersion2 { if len(p) != 9 { - return frameHeader{}, fmt.Errorf("not enough bytes to read header require 9 got: %d", len(p)) + return frameHeader{}, fmt.Errorf("gocql: not enough bytes to read header require 9 got: %d", len(p)) } head.stream = int(int16(p[2])<<8 | int16(p[3])) @@ -477,7 +477,7 @@ func readHeader(r io.Reader, p []byte) (head frameHeader, err error) { head.length = int(readInt(p[5:])) } else { if len(p) != 8 { - return frameHeader{}, fmt.Errorf("not enough bytes to read header require 8 got: %d", len(p)) + return frameHeader{}, fmt.Errorf("gocql: not enough bytes to read header require 8 got: %d", len(p)) } head.stream = int(int8(p[2])) @@ -501,12 +501,12 @@ func (f *framer) payload() { // reads a frame form the wire into the framers buffer func (f *framer) readFrame(r io.Reader, head *frameHeader) error { if head.length < 0 { - return fmt.Errorf("frame body length can not be less than 0: %d", head.length) + return fmt.Errorf("gocql: frame body length can not be less than 0: %d", head.length) } else if head.length > maxFrameSize { // need to free up the connection to be used again _, err := io.CopyN(ioutil.Discard, r, int64(head.length)) if err != nil { - return fmt.Errorf("error whilst trying to discard frame with invalid length: %v", err) + return fmt.Errorf("gocql: error whilst trying to discard frame with invalid length: %w", err) } return ErrFrameTooBig } @@ -521,7 +521,7 @@ func (f *framer) readFrame(r io.Reader, head *frameHeader) error { // assume the underlying reader takes care of timeouts and retries n, err := io.ReadFull(r, f.buf) if err != nil { - return fmt.Errorf("unable to read frame body: read %d/%d bytes: %v", n, head.length, err) + return fmt.Errorf("gocql: unable to read frame body: read %d/%d bytes: %w", n, head.length, err) } if head.flags&flagCompress == flagCompress { @@ -531,7 +531,7 @@ func (f *framer) readFrame(r io.Reader, head *frameHeader) error { f.buf, err = f.compres.Decode(f.buf) if err != nil { - return err + return fmt.Errorf("gocql: %w", err) } } @@ -707,7 +707,7 @@ func (f *framer) parseErrorFrame() frame { // TODO(zariel): we should have some distinct types for these errors return errD default: - panic(fmt.Errorf("unknown error code: 0x%x", errD.code)) + panic(fmt.Errorf("gocql: unknown error code: 0x%x", errD.code)) } } @@ -776,7 +776,7 @@ func (f *framer) finish() error { // TODO: only compress frames which are big enough compressed, err := f.compres.Encode(f.buf[f.headSize:]) if err != nil { - return err + return fmt.Errorf("gocql: %w", err) } f.buf = append(f.buf[:f.headSize], compressed...) @@ -856,7 +856,7 @@ func (w *writePrepareFrame) buildFrame(f *framer, streamID int) error { if f.proto > protoVersion4 { flags |= flagWithPreparedKeyspace } else { - panic(fmt.Errorf("the keyspace can only be set with protocol 5 or higher")) + panic(fmt.Errorf("gocql: the keyspace can only be set with protocol 5 or higher")) } } if f.proto > protoVersion4 { @@ -955,7 +955,7 @@ func (f *framer) parsePreparedMetadata() preparedMetadata { meta.flags = f.readInt() meta.colCount = f.readInt() if meta.colCount < 0 { - panic(fmt.Errorf("received negative column count: %d", meta.colCount)) + panic(fmt.Errorf("gocql: received negative column count: %d", meta.colCount)) } meta.actualColCount = meta.colCount @@ -1052,7 +1052,7 @@ func (f *framer) parseResultMetadata() resultMetadata { meta.flags = f.readInt() meta.colCount = f.readInt() if meta.colCount < 0 { - panic(fmt.Errorf("received negative column count: %d", meta.colCount)) + panic(fmt.Errorf("gocql: received negative column count: %d", meta.colCount)) } meta.actualColCount = meta.colCount @@ -1139,7 +1139,7 @@ func (f *framer) parseResultRows() frame { result.numRows = f.readInt() if result.numRows < 0 { - panic(fmt.Errorf("invalid row_count in result frame: %d", result.numRows)) + panic(fmt.Errorf("gocql: invalid row_count in result frame: %d", result.numRows)) } return result @@ -1507,7 +1507,7 @@ func (f *framer) writeQueryParams(opts *queryParams) { if f.proto > protoVersion4 { flags |= flagWithKeyspace } else { - panic(fmt.Errorf("the keyspace can only be set with protocol 5 or higher")) + panic(fmt.Errorf("gocql: the keyspace can only be set with protocol 5 or higher")) } } @@ -1770,7 +1770,7 @@ func (f *framer) writeRegisterFrame(streamID int, w *writeRegisterFrame) error { func (f *framer) readByte() byte { if len(f.buf) < 1 { - panic(fmt.Errorf("not enough bytes in buffer to read byte require 1 got: %d", len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read byte require 1 got: %d", len(f.buf))) } b := f.buf[0] @@ -1780,7 +1780,7 @@ func (f *framer) readByte() byte { func (f *framer) readInt() (n int) { if len(f.buf) < 4 { - panic(fmt.Errorf("not enough bytes in buffer to read int require 4 got: %d", len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read int require 4 got: %d", len(f.buf))) } n = int(int32(f.buf[0])<<24 | int32(f.buf[1])<<16 | int32(f.buf[2])<<8 | int32(f.buf[3])) @@ -1790,7 +1790,7 @@ func (f *framer) readInt() (n int) { func (f *framer) readShort() (n uint16) { if len(f.buf) < 2 { - panic(fmt.Errorf("not enough bytes in buffer to read short require 2 got: %d", len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read short require 2 got: %d", len(f.buf))) } n = uint16(f.buf[0])<<8 | uint16(f.buf[1]) f.buf = f.buf[2:] @@ -1801,7 +1801,7 @@ func (f *framer) readString() (s string) { size := f.readShort() if len(f.buf) < int(size) { - panic(fmt.Errorf("not enough bytes in buffer to read string require %d got: %d", size, len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read string require %d got: %d", size, len(f.buf))) } s = string(f.buf[:size]) @@ -1813,7 +1813,7 @@ func (f *framer) readLongString() (s string) { size := f.readInt() if len(f.buf) < size { - panic(fmt.Errorf("not enough bytes in buffer to read long string require %d got: %d", size, len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read long string require %d got: %d", size, len(f.buf))) } s = string(f.buf[:size]) @@ -1823,7 +1823,7 @@ func (f *framer) readLongString() (s string) { func (f *framer) readUUID() *UUID { if len(f.buf) < 16 { - panic(fmt.Errorf("not enough bytes in buffer to read uuid require %d got: %d", 16, len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read uuid require %d got: %d", 16, len(f.buf))) } // TODO: how to handle this error, if it is a uuid, then sureley, problems? @@ -1850,7 +1850,7 @@ func (f *framer) readBytesInternal() ([]byte, error) { } if len(f.buf) < size { - return nil, fmt.Errorf("not enough bytes in buffer to read bytes require %d got: %d", size, len(f.buf)) + return nil, fmt.Errorf("gocql: not enough bytes in buffer to read bytes require %d got: %d", size, len(f.buf)) } l := f.buf[:size] @@ -1871,7 +1871,7 @@ func (f *framer) readBytes() []byte { func (f *framer) readShortBytes() []byte { size := f.readShort() if len(f.buf) < int(size) { - panic(fmt.Errorf("not enough bytes in buffer to read short bytes: require %d got %d", size, len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read short bytes: require %d got %d", size, len(f.buf))) } l := f.buf[:size] @@ -1882,18 +1882,18 @@ func (f *framer) readShortBytes() []byte { func (f *framer) readInetAdressOnly() net.IP { if len(f.buf) < 1 { - panic(fmt.Errorf("not enough bytes in buffer to read inet size require %d got: %d", 1, len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read inet size require %d got: %d", 1, len(f.buf))) } size := f.buf[0] f.buf = f.buf[1:] if !(size == 4 || size == 16) { - panic(fmt.Errorf("invalid IP size: %d", size)) + panic(fmt.Errorf("gocql: invalid IP size: %d", size)) } if len(f.buf) < 1 { - panic(fmt.Errorf("not enough bytes in buffer to read inet require %d got: %d", size, len(f.buf))) + panic(fmt.Errorf("gocql: not enough bytes in buffer to read inet require %d got: %d", size, len(f.buf))) } ip := make([]byte, size) diff --git a/helpers.go b/helpers.go index f2faee9e0..09bb665c2 100644 --- a/helpers.go +++ b/helpers.go @@ -97,7 +97,7 @@ func goType(t TypeInfo) (reflect.Type, error) { case TypeDuration: return reflect.TypeOf(*new(Duration)), nil default: - return nil, fmt.Errorf("cannot create Go type for unknown CQL type %s", t) + return nil, fmt.Errorf("gocql: cannot create Go type for unknown CQL type %s", t) } } diff --git a/host_source.go b/host_source.go index a0bab9ad0..a88337f92 100644 --- a/host_source.go +++ b/host_source.go @@ -35,8 +35,12 @@ import ( "time" ) -var ErrCannotFindHost = errors.New("cannot find host") -var ErrHostAlreadyExists = errors.New("host already exists") +var ( + ErrRefreshWhenStopRequested = errors.New("gocql: could not refresh ring because stop was requested") + ErrCannotFindHost = errors.New("gocql: cannot find host") + ErrHostAlreadyExists = errors.New("gocql: host already exists") + ErrZeroRowsReturned = errors.New("gocql: query returned 0 rows") +) type nodeState int32 @@ -76,24 +80,24 @@ func (c *cassVersion) unmarshal(data []byte) error { v := strings.Split(version, ".") if len(v) < 2 { - return fmt.Errorf("invalid version string: %s", data) + return fmt.Errorf("gocql: invalid version string: %s", data) } var err error c.Major, err = strconv.Atoi(v[0]) if err != nil { - return fmt.Errorf("invalid major version %v: %v", v[0], err) + return fmt.Errorf("gocql: invalid major version %v: %v", v[0], err) } c.Minor, err = strconv.Atoi(v[1]) if err != nil { - return fmt.Errorf("invalid minor version %v: %v", v[1], err) + return fmt.Errorf("gocql: invalid minor version %v: %v", v[1], err) } if len(v) > 2 { c.Patch, err = strconv.Atoi(v[2]) if err != nil { - return fmt.Errorf("invalid patch version %v: %v", v[2], err) + return fmt.Errorf("gocql: invalid patch version %v: %v", v[2], err) } } @@ -472,7 +476,7 @@ func checkSystemSchema(control *controlConn) (bool, error) { // Given a map that represents a row from either system.local or system.peers // return as much information as we can in *HostInfo func (s *Session) hostInfoFromMap(row map[string]interface{}, host *HostInfo) (*HostInfo, error) { - const assertErrorMsg = "Assertion failed for %s" + const assertErrorMsg = "gocql: Assertion failed for %s" var ok bool // Default to our connected port if the cluster doesn't have port information @@ -598,7 +602,7 @@ func (s *Session) hostInfoFromIter(iter *Iter, connectAddress net.IP, defaultPor } if len(rows) == 0 { - return nil, errors.New("query returned 0 rows") + return nil, ErrZeroRowsReturned } host, err := s.hostInfoFromMap(rows[0], &HostInfo{connectAddress: connectAddress, port: defaultPort}) @@ -624,7 +628,7 @@ func (r *ringDescriber) getLocalHostInfo() (*HostInfo, error) { host, err := r.session.hostInfoFromIter(iter, nil, r.session.cfg.Port) if err != nil { - return nil, fmt.Errorf("could not retrieve local host info: %w", err) + return nil, fmt.Errorf("gocql: could not retrieve local host info: %w", err) } return host, nil } @@ -647,7 +651,7 @@ func (r *ringDescriber) getClusterPeerInfo(localHost *HostInfo) ([]*HostInfo, er rows, err := iter.SliceMap() if err != nil { // TODO(zariel): make typed error - return nil, fmt.Errorf("unable to fetch peer host info: %s", err) + return nil, fmt.Errorf("gocql: unable to fetch peer host info: %w", err) } for _, row := range rows { @@ -710,7 +714,7 @@ func (s *Session) debounceRingRefresh() { func (s *Session) refreshRing() error { err, ok := <-s.ringRefresher.refreshNow() if !ok { - return errors.New("could not refresh ring because stop was requested") + return ErrRefreshWhenStopRequested } return err @@ -736,7 +740,7 @@ func refreshRing(r *ringDescriber) error { newHostID := h.HostID() existing, ok := prevHosts[newHostID] if !ok { - return fmt.Errorf("get existing host=%s from prevHosts: %w", h, ErrCannotFindHost) + return fmt.Errorf("gocql: get existing host=%s from prevHosts: %w", h, ErrCannotFindHost) } if h.connectAddress.Equal(existing.connectAddress) && h.nodeToNodeAddress().Equal(existing.nodeToNodeAddress()) { // no host IP change @@ -746,7 +750,7 @@ func refreshRing(r *ringDescriber) error { // remove old HostInfo (w/old IP) r.session.removeHost(existing) if _, alreadyExists := r.session.ring.addHostIfMissing(h); alreadyExists { - return fmt.Errorf("add new host=%s after removal: %w", h, ErrHostAlreadyExists) + return fmt.Errorf("gocql: add new host=%s after removal: %w", h, ErrHostAlreadyExists) } // add new HostInfo (same hostID, new IP) r.session.startPoolFill(h) diff --git a/marshal.go b/marshal.go index 4d0adb923..9ded19a5d 100644 --- a/marshal.go +++ b/marshal.go @@ -47,7 +47,7 @@ var ( ) var ( - ErrorUDTUnavailable = errors.New("UDT are not available on protocols less than 3, please update config") + ErrorUDTUnavailable = errors.New("gocql: UDT are not available on protocols less than 3, please update config") ) // Marshaler is the interface implemented by objects that can marshal @@ -178,7 +178,7 @@ func Marshal(info TypeInfo, value interface{}) ([]byte, error) { } // TODO(tux21b): add the remaining types - return nil, fmt.Errorf("can not marshal %T into %s", value, info) + return nil, marshalErrorf("can not marshal %T into %s", value, info) } // Unmarshal parses the CQL encoded data based on the info parameter that @@ -282,7 +282,7 @@ func Unmarshal(info TypeInfo, data []byte, value interface{}) error { } // TODO(tux21b): add the remaining types - return fmt.Errorf("can not unmarshal %s into %T", info, value) + return unmarshalErrorf("can not unmarshal %s into %T", info, value) } func isNullableValue(value interface{}) bool { @@ -2733,15 +2733,17 @@ func (m MarshalError) Error() string { } func marshalErrorf(format string, args ...interface{}) MarshalError { - return MarshalError(fmt.Sprintf(format, args...)) + return MarshalError(fmt.Sprintf(gocqlErr+format, args...)) } type UnmarshalError string +const gocqlErr = "gocql: " + func (m UnmarshalError) Error() string { return string(m) } func unmarshalErrorf(format string, args ...interface{}) UnmarshalError { - return UnmarshalError(fmt.Sprintf(format, args...)) + return UnmarshalError(fmt.Sprintf(gocqlErr+format, args...)) } diff --git a/metadata.go b/metadata.go index 6eb798f8a..257cea62d 100644 --- a/metadata.go +++ b/metadata.go @@ -221,7 +221,7 @@ func columnKindFromSchema(kind string) (ColumnKind, error) { case "static": return ColumnStatic, nil default: - return -1, fmt.Errorf("unknown column kind: %q", kind) + return -1, fmt.Errorf("gocql: unknown column kind: %q", kind) } } @@ -585,7 +585,7 @@ func getKeyspaceMetadata(session *Session, keyspaceName string) (*KeyspaceMetada iter.Scan(&keyspace.DurableWrites, &replication) err := iter.Close() if err != nil { - return nil, fmt.Errorf("error querying keyspace schema: %v", err) + return nil, fmt.Errorf("gocql: error querying keyspace schema: %w", err) } keyspace.StrategyClass = replication["class"] @@ -611,7 +611,7 @@ func getKeyspaceMetadata(session *Session, keyspaceName string) (*KeyspaceMetada iter.Scan(&keyspace.DurableWrites, &keyspace.StrategyClass, &strategyOptionsJSON) err := iter.Close() if err != nil { - return nil, fmt.Errorf("error querying keyspace schema: %v", err) + return nil, fmt.Errorf("gocql: error querying keyspace schema: %w", err) } err = json.Unmarshal(strategyOptionsJSON, &keyspace.StrategyOptions) @@ -754,7 +754,7 @@ func getTableMetadata(session *Session, keyspaceName string) ([]TableMetadata, e err := iter.Close() if err != nil && err != ErrNotFound { - return nil, fmt.Errorf("error querying table schema: %v", err) + return nil, fmt.Errorf("gocql: error querying table schema: %w", err) } return tables, nil @@ -941,7 +941,7 @@ func getColumnMetadata(session *Session, keyspaceName string) ([]ColumnMetadata, } if err != nil && err != ErrNotFound { - return nil, fmt.Errorf("error querying column schema: %v", err) + return nil, fmt.Errorf("gocql: error querying column schema: %w", err) } return columns, nil diff --git a/policies.go b/policies.go index 1157da87b..c6b606a0b 100644 --- a/policies.go +++ b/policies.go @@ -135,7 +135,7 @@ const ( // ErrUnknownRetryType is returned if the retry policy returns a retry type // unknown to the query executor. -var ErrUnknownRetryType = errors.New("unknown retry type returned by retry policy") +var ErrUnknownRetryType = errors.New("gocql: unknown retry type returned by retry policy") // RetryPolicy interface is used by gocql to determine if a query can be attempted // again after a retryable error has been received. The interface allows gocql diff --git a/session.go b/session.go index a600b95f3..fb946810b 100644 --- a/session.go +++ b/session.go @@ -127,7 +127,7 @@ func addrsToHosts(addrs []string, defaultPort int, logger StdLogger) ([]*HostInf hosts = append(hosts, resolvedHosts...) } if len(hosts) == 0 { - return nil, errors.New("failed to resolve any of the provided hostnames") + return nil, ErrFailedResolveHostnames } return hosts, nil } @@ -141,7 +141,7 @@ func NewSession(cfg ClusterConfig) (*Session, error) { // Check that either Authenticator is set or AuthProvider, not both if cfg.Authenticator != nil && cfg.AuthProvider != nil { - return nil, errors.New("Can't use both Authenticator and AuthProvider in cluster config.") + return nil, ErrAuthenticatorAndAuthProvider } // TODO: we should take a context in here at some point @@ -192,7 +192,7 @@ func NewSession(cfg ClusterConfig) (*Session, error) { connCfg, err := connConfig(&s.cfg) if err != nil { //TODO: Return a typed error - return nil, fmt.Errorf("gocql: unable to create session: %v", err) + return nil, fmt.Errorf("gocql: unable to create session: %w", err) } s.connCfg = connCfg @@ -204,7 +204,7 @@ func NewSession(cfg ClusterConfig) (*Session, error) { return nil, ErrNoConnectionsStarted } else { // TODO(zariel): dont wrap this error in fmt.Errorf, return a typed error - return nil, fmt.Errorf("gocql: unable to create session: %v", err) + return nil, fmt.Errorf("gocql: unable to create session: %w", err) } } @@ -223,9 +223,9 @@ func (s *Session) init() error { if s.cfg.ProtoVersion == 0 { proto, err := s.control.discoverProtocol(hosts) if err != nil { - return fmt.Errorf("unable to discover protocol version: %v", err) + return fmt.Errorf("gocql: unable to discover protocol version: %w", err) } else if proto == 0 { - return errors.New("unable to discovery protocol version") + return errors.New("gocql: unable to discovery protocol version") } // TODO(zariel): we really only need this in 1 place @@ -2279,22 +2279,22 @@ func (e Error) Error() string { } var ( - ErrNotFound = errors.New("not found") - ErrUnavailable = errors.New("unavailable") - ErrUnsupported = errors.New("feature not supported") - ErrTooManyStmts = errors.New("too many statements") - ErrUseStmt = errors.New("use statements aren't supported. Please see https://github.com/apache/cassandra-gocql-driver for explanation.") - ErrSessionClosed = errors.New("session has been closed") - ErrNoConnections = errors.New("gocql: no hosts available in the pool") - ErrNoKeyspace = errors.New("no keyspace provided") - ErrKeyspaceDoesNotExist = errors.New("keyspace does not exist") - ErrNoMetadata = errors.New("no metadata available") + ErrNotFound = errors.New("gocql: not found") + ErrUnsupported = errors.New("gocql: feature not supported") + ErrTooManyStmts = errors.New("gocql: too many statements") + ErrUseStmt = errors.New("gocql: use statements aren't supported. Please see https://github.com/apache/cassandra-gocql-driver for explanation.") + ErrSessionClosed = errors.New("gocql: session has been closed") + ErrNoConnections = errors.New("gocql: no hosts available in the pool") + ErrNoKeyspace = errors.New("gocql: no keyspace provided") + ErrKeyspaceDoesNotExist = errors.New("gocql: keyspace does not exist") + ErrNoMetadata = errors.New("gocql: no metadata available") + ErrFailedResolveHostnames = errors.New("gocql: failed to resolve any of the provided hostnames") ) type ErrProtocol struct{ error } func NewErrProtocol(format string, args ...interface{}) error { - return ErrProtocol{fmt.Errorf(format, args...)} + return ErrProtocol{fmt.Errorf(gocqlErr+format, args...)} } // BatchSizeMaximum is the maximum number of statements a batch operation can have. diff --git a/token.go b/token.go index 7502ea713..e7b6b0423 100644 --- a/token.go +++ b/token.go @@ -177,7 +177,7 @@ func newTokenRing(partitioner string, hosts []*HostInfo) (*tokenRing, error) { } else if strings.HasSuffix(partitioner, "RandomPartitioner") { tokenRing.partitioner = randomPartitioner{} } else { - return nil, fmt.Errorf("unsupported partitioner '%s'", partitioner) + return nil, fmt.Errorf("gocql: unsupported partitioner '%s'", partitioner) } for _, host := range hosts { diff --git a/topology.go b/topology.go index 2fc38a887..ae2f888ce 100644 --- a/topology.go +++ b/topology.go @@ -74,19 +74,19 @@ func getReplicationFactorFromOpts(val interface{}) (int, error) { switch v := val.(type) { case int: if v < 0 { - return 0, fmt.Errorf("invalid replication_factor %d", v) + return 0, fmt.Errorf("gocql: invalid replication_factor %d", v) } return v, nil case string: n, err := strconv.Atoi(v) if err != nil { - return 0, fmt.Errorf("invalid replication_factor %q: %v", v, err) + return 0, fmt.Errorf("gocql: invalid replication_factor %q: %w", v, err) } else if n < 0 { - return 0, fmt.Errorf("invalid replication_factor %d", n) + return 0, fmt.Errorf("gocql: invalid replication_factor %d", n) } return n, nil default: - return 0, fmt.Errorf("unknown replication_factor type %T", v) + return 0, fmt.Errorf("gocql: unknown replication_factor type %T", v) } } diff --git a/udt_test.go b/udt_test.go index f1980f243..7c7e67d21 100644 --- a/udt_test.go +++ b/udt_test.go @@ -180,7 +180,7 @@ func TestUDT_Proto2error(t *testing.T) { // TODO(zariel): move this to marshal test? _, err := Marshal(NativeType{custom: "org.apache.cassandra.db.marshal.UserType.Type", proto: 2}, 1) if err != ErrorUDTUnavailable { - t.Fatalf("expected %v got %v", ErrUnavailable, err) + t.Fatalf("expected %v got %v", ErrorUDTUnavailable, err) } } diff --git a/uuid.go b/uuid.go index cc5f1c21f..561b4a142 100644 --- a/uuid.go +++ b/uuid.go @@ -95,12 +95,12 @@ func ParseUUID(input string) (UUID, error) { case r >= 'A' && r <= 'F' && j < 32: u[j/2] |= byte(r-'A'+10) << uint(4-j&1*4) default: - return UUID{}, fmt.Errorf("invalid UUID %q", input) + return UUID{}, fmt.Errorf("gocql: invalid UUID %q", input) } j += 1 } if j != 32 { - return UUID{}, fmt.Errorf("invalid UUID %q", input) + return UUID{}, fmt.Errorf("gocql: invalid UUID %q", input) } return u, nil } @@ -323,7 +323,7 @@ func (u UUID) MarshalJSON() ([]byte, error) { func (u *UUID) UnmarshalJSON(data []byte) error { str := strings.Trim(string(data), `"`) if len(str) > 36 { - return fmt.Errorf("invalid JSON UUID %s", str) + return fmt.Errorf("gocql: invalid JSON UUID %s", str) } parsed, err := ParseUUID(str)