Home > Net >  errors.Is() doesn't function propertly
errors.Is() doesn't function propertly

Time:09-28

I pasted a section of code that was supposed to catch an AllTopologyNodesDownError error which doesn't work and I have no idea why.

func (sc *ServerConfig) addNodesToCluster(store *ravendb.DocumentStore) error {
        clusterTopology, err := sc.getClusterTopology(store)
        if errors.Is(err, &ravendb.AllTopologyNodesDownError{}) {
            for _, url := range sc.Url.List {
                    err = addNodeToCluster(store, url)
                    if err != nil {
                        return err
                    }
            }
        } else if err != nil {
            return err
        }

the structure of the ravendb.AllTopologyNodesDownError is

// AllTopologyNodesDownError represents "all topology nodes are down" error
type AllTopologyNodesDownError struct {
    errorBase
} 

type errorBase struct {
    wrapped  error
    ErrorStr string
}

screen shot of the error when debugging the code

CodePudding user response:

errors.Is() is used to tell if any error in the chain is the same instance as the provided error1, that can never be the case here because you provided a literal of your error type, no other code could hold that instance or a reference to it.

Your error looks like a type, to tell if any error in the chain is a given type you should use errors.As():

clusterTopology, err := sc.getClusterTopology(store)
var errAllDown *AllTopologyNodesDownError
if errors.As(err, &errAllDown) {
    // err had an *AllTopologyNodesDownError in its
    // chain and errAllDown now contains it.
}

  1. Can be overridden by implementing the Unwrap() interface which your error type does not.
  •  Tags:  
  • go
  • Related