英文:
errors.Is() doesn't function propertly
问题
我贴了一段代码,本来应该捕获AllTopologyNodesDownError
错误,但是它没有起作用,我不知道为什么。
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
}
}
ravendb.AllTopologyNodesDownError
的结构如下:
// AllTopologyNodesDownError represents "all topology nodes are down" error
type AllTopologyNodesDownError struct {
errorBase
}
type errorBase struct {
wrapped error
ErrorStr string
}
英文:
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
}
答案1
得分: 0
errors.Is()
用于判断链中的任何错误是否与提供的错误实例相同,但在这种情况下不可能发生,因为您提供了一个字面量的错误类型,其他代码不可能持有该实例或对其的引用。
您的错误看起来像是一个类型,要判断链中的任何错误是否为给定类型,您应该使用 errors.As()
:
clusterTopology, err := sc.getClusterTopology(store)
var errAllDown *AllTopologyNodesDownError
if errors.As(err, &errAllDown) {
// err 在其链中有一个 *AllTopologyNodesDownError
// errAllDown 现在包含它。
}
- 可以通过实现
Unwrap()
接口来覆盖此行为,但您的错误类型没有实现该接口。
英文:
errors.Is()
is used to tell if any error in the chain is the same instance as the provided error<sup>1</sup>, 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.
}
<hr>
- Can be overridden by implementing the
Unwrap()
interface which your error type does not.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论