
问题内容
当我有一个包含嵌套在其中的切片的错误结构时,Error.Is 似乎无法正常工作:
package main
import (
"errors"
"fmt"
"os"
)
type Response struct {
Details []string
}
type ErrResponseError struct {
Response Response
}
func (err ErrResponseError) Error() string {
return "response error"
}
func main() {
err := ErrResponseError{}
fmt.Fprintf(os.Stdout, "equal: %v", errors.Is(err, ErrResponseError{}))
}
返回
equal: false
package main
import (
"errors"
"fmt"
"os"
)
type Response struct {
Details string // Changed this line
}
type ErrResponseError struct {
Response Response
}
func (err ErrResponseError) Error() string {
return "response error"
}
func main() {
err := ErrResponseError{}
fmt.Fprintf(os.Stdout, "equal: %v", errors.Is(err, ErrResponseError{}))
}
返回
equal: true
...................................................... ...................................................... ...................................................... ...................................................... ......................................
解决方法
来自文档:
因此,您可以通过编写一个 Is 方法来比较两个切片来完成此操作。
默认的误差比较算法检查误差是否等于目标。由于您的错误包含一个切片,因此它不具有可比性。










